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"
}
}
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"
}
}
*/