I have this array of objects returned by a SQL query where top_id is my parent ID field:
Array (
[0] => stdClass Object ( [id] => 1 [top_id] => 0 [name] => Cat 1 )
[1] => stdClass Object ( [id] => 2 [top_id] => 0 [name] => Cat 2 )
[2] => stdClass Object ( [id] => 3 [top_id] => 0 [name] => Cat 3 )
[3] => stdClass Object ( [id] => 4 [top_id] => 2 [name] => Subcat 1 )
[4] => stdClass Object ( [id] => 5 [top_id] => 2 [name] => Subcat 2 )
[5] => stdClass Object ( [id] => 6 [top_id] => 3 [name] => Subcat 3 )
[6] => stdClass Object ( [id] => 7 [top_id] => 5 [name] => Subcat 4 )
)
Now I need to obtain a nested list like this using PHP:
<ul>
<li>Cat 1</li>
<li>Cat 2
<ul>
<li>Subcat 1</li>
<li>Subcat 2
<ul>
<il>Subcat 3
<ul>
<li>Subcat 4</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>Cat 3</li>
</ul>
Any idea? Thanks
First of all map the objects onto a new hash (array) in which the index is the
id
:Then transpose this flat hash into a tree-like structure, see this answer for another code example, it's merely the same here:
Finally you can output this tree-like structure as HTML. This can be done with either a stack or recursive. This is one variant with recursion:
Output:
Full code Example + HTML Demo.