I have an array of categories that looks something like
array(
array(
'id' => '1',
'path' => '1',
'children_count' => '16',
'name' => 'A'
),
array(
'id' => '3',
'path' => '1/2/3',
'children_count' => '0',
'name' => 'C'
),
array(
'id' => '2',
'path' => '1/2',
'children_count' => '9',
'name' => 'B'
),
array(
'id' => '4',
'path' => '1/2/4',
'children_count' => '0',
'name' => 'D'
)
)
What I'm trying to build is a hierarchal array (the path
key shows the relation based on id
), so the output is in the correct order (root parent first, then children, then more children) and indent the name
based on how far down in the child is. The end result should look something like:
A
-B
--C
--D
Here's what I have so far, but it's obviously not working
$categoryTree = array();
foreach ($categories as $category) {
$categoryTree[(string)$category['path']] = str_repeat("-", substr_count($category['path'], "/")) . $category['name'];
}
ksort($categoryTree);
var_export($categoryTree);
Which comes out to:
array (
'1/2' => '-B',
'1/2/3' => '--C',
'1/2/4' => '--D',
1 => 'A'
)
How can I get these in the correct order? (and if siblings could be ordered by id
that would be dandy too)