I have been puzzling with this problem for days, without any luck. I hope some of you can help. From my database I get a list of files, which various information attached, including a virtual path. Some typical data is:
Array
(
[0] => Array
(
[name] => guide_to_printing.txt
[virtual_path] => guides/it
)
[1] => Array
(
[name] => guide_to_vpn.txt
[virtual_path] => guides/it
)
[2] => Array
(
[name] => for_new_employees.txt
[virtual_path] => guides
)
)
I wish to convert this into a hierarchical array structure from the virtual paths, so the output of the above should be:
Array
(
[0] => Array
(
[type] => dir
[name] => guides
[children] => Array
(
[0] => Array
(
[type] => dir
[name] => it
[children] = Array
(
[0] => Array
(
[type] => file
[name] => guide_to_printing.txt
)
[1] => Array
(
[type] => file
[name] => guide_to_vpn.txt
)
)
)
[1] => Array
(
[type] => file
[name] => for_new_employees.txt
)
)
)
)
Where the type property indicates if it is a directory or a file.
Can someone help with creating a function which does this conversion. It will be of great help. Thanks.
My own best solution so far is:
foreach($docs as $doc) {
$path = explode("/",$doc['virtual_path']);
$arrayToInsert = array(
'name' => $doc['name'],
'path' => $doc['virtual_path'],
);
if(count($path)==1) { $r[$path[0]][] = $arrayToInsert; }
if(count($path)==2) { $r[$path[0]][$path[1]][] = $arrayToInsert; }
if(count($path)==3) { $r[$path[0]][$path[1]][$path[2]][] = $arrayToInsert; }
}
Of course this only works for a depth of 3 in the directory structure, and the keys are the directory names.