having this array of file paths
paths: Array
(
[0] => folder1/content/file1.php
[1] => folder1/content/file2.php
[2] => folder1/edit/file1.php
[3] => folder1/edit/file2.php
[4] => folder1/pagination/file1.php
[5] => folder1/pagination/file2.php
[6] => folder1/toolbar/file1.php
[7] => folder1/toolbar/file2.php
[8] => folder2/cms/html/file1.php
[9] => folder2/cms/html/file2.php
)
how can I parse it memory-efficiently into an HTML-grouped-list-element? The final grouping must look like:
final: Array
(
[folder1] => Array
(
[content] => Array
(
[0] => file1.php
[1] => file2.php
)
[edit] => Array
(
[0] => file1.php
[1] => file2.php
)
[pagination] => Array
(
[0] => file1.php
[1] => file2.php
)
[toolbar] => Array
(
[0] => file1.php
[1] => file2.php
)
)
[folder2] => Array
(
[cms] => Array
(
[html] => Array
(
[0] => file1.php
[1] => file2.php
)
)
)
)
I noticed the paths are of variable depths and stuck with this problem. The parsing routine must not be fixed to a specified recursion level. It rather iterates over a file path until the file name is left and adds this file to the array. I tried several approaches - the foreach loop, array_walk() and array_reduce(), but cannot achieve what I want.
EDIT
Here is my final try to satifiy those in doubt about my effort to find a solution myself before asking:
$groups = [];
foreach ($paths as $path)
{
$pieces = explode(DIRECTORY_SEPARATOR, $path);
if (!array_key_exists(($first = array_shift($pieces)), $groups))
{
$groups[$first] = [];
// Mhm ... how to recoursively nest further
// arrays for every path level left?
}
}