Answer the question
In order to leave comments, you need to log in
How to split path into arrays like file/folder + parent folder?
It is necessary to split the file path into an array with arrays containing two values: the file/folder name and the child folder name.
For example, there is a path /dir1/dir2/file.txt , it needs to be split so that the output is something like this:
array(3) {
[0]=>
array(2) {
["file_name"]=>
string(4) "dir1"
["parent_file"]=>
string(0) ""
}
[1]=>
array(2) {
["file_name"]=>
string(4) "dir2"
["parent_file"]=>
string(4) "dir1"
}
[2]=>
array(2) {
["file_name"]=>
string(8) "file.txt"
["parent_file"]=>
string(4) "dir2"
}
}
Answer the question
In order to leave comments, you need to log in
function extractPathElements(string $path): array
{
$explodedPath = explode('/', $path);
$pathTree = [];
foreach ($explodedPath as $key => $value) {
if (!$value) {
continue;
}
$pathTree[] = [
'file_name' => $value,
'parent_file' => $explodedPath[$key-1] ?? '',
];
}
return $pathTree;
}
// client code
var_dump(extractPathElements('/dir1/dir2/file.txt'));
/*
array(3) {
[0]=>
array(2) {
["file_name"]=>
string(4) "dir1"
["parent_file"]=>
string(0) ""
}
[1]=>
array(2) {
["file_name"]=>
string(4) "dir2"
["parent_file"]=>
string(4) "dir1"
}
[2]=>
array(2) {
["file_name"]=>
string(8) "file.txt"
["parent_file"]=>
string(4) "dir2"
}
}
*/
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question