I want to traverse this array and display, ‘comment’ as bullet points.
Array
(
[1] => Array
(
[id] => 1
[comment] => a
[parent_id] => 0
[children] => Array
(
[3] => Array
(
[id] => 3
[comment] => c
[parent_id] => 1
[depth] => 0
[child_count] => 0
[children] =>
)
[4] => Array
(
[id] => 4
[comment] => d
[parent_id] => 1
[depth] => 0
[child_count] => 0
[children] =>
)
)
[depth] => 1
[child_count] => 2
)
[2] => Array
(
[id] => 2
[comment] => b
[parent_id] => 0
[children] => Array
(
[5] => Array
(
[id] => 5
[comment] => e
[parent_id] => 2
[children] => Array
(
[7] => Array
(
[id] => 7
[comment] => g
[parent_id] => 5
[children] => Array
(
[8] => Array
(
[id] => 8
[comment] => h
[parent_id] => 7
[children] => Array
(
[9] => Array
(
[id] => 8
[comment] => h
[parent_id] => 8
[children] => Array
(
[10] => Array
(
[id] => 8
[comment] => h
[parent_id] => 9
[depth] => 0
[child_count] => 0
[children] =>
)
)
[depth] => 1
[child_count] => 1
)
)
[depth] => 2
[child_count] => 1
)
)
[depth] => 3
[child_count] => 1
)
)
[depth] => 4
[child_count] => 1
)
[6] => Array
(
[id] => 6
[comment] => f
[parent_id] => 2
[depth] => 0
[child_count] => 0
[children] =>
)
)
[depth] => 5
[child_count] => 2
)
)
Here you go, my hierTree() function by default prints nested ul or ol lists, for an undetermined depth of nested arrays, this function will work out of the box for the example array provided in your question.
The output of this function will be nicely indented for it to be easily readable.
Also, If you do
hierTree($tree, 'ol'); you will get an ordered list. Id you do hierTree($tree, 'ol', 'id');You will get an ordered tree and the id field will be print instead of the default comment one.Inserting classes.
If you want to have different classes per list element so you can more easily style on CSS. (although I would recomment to use CSS direct descendant selectors (“>”))
This slightly modified version will print a depthN class per list element.
So you can then target their *LI*s by a simple CSS rule such as
ul.depth1 > li { ....