I am at a little bit of a loss as to how to approach this, I suspect foreach
is not the right answer, and I am aware of the existence of array_walk()
and RecursiveArrayIterator
, but I have no real-world experience of using either, so I could do with a bit of a pointer in the right direction. (I am working with PHP 7.1.9 if it makes any difference to the answer).
Source data
I have a single-dimension array that contains a parent/child tree of objects. You can assume the tree has unknown and variable nesting depth. A basic example would look like the following :
$sampleParent=array("id"=>101,"level"=>1,"parent_id"=>1,"name"=>"parent","otherparam"=>"bar");
$sampleChildD1=array("id"=>234,"level"=>2,"parent_id"=>101,"name"=>"level1","otherparam"=>"bar");
$sampleChildD2=array("id"=>499,"level"=>3,"parent_id"=>234,"name"=>"level2","otherparam"=>"bar");
$sampleTree=array($sampleParent,$sampleChildD1,$sampleChildD2);
Desired output
The ultimate goal is to output HTML lists (i.e. <ul><li></li></ul>
), one list per parent. Nesting of children achieved by nesting <ul>
tags. So for my example above :
<ul>
<li>
<a href="#">parent</a>
</li>
<ul>
<li>
<a href="#">level1</a>
<ul>
<li>
<a href="#">level2</a>
</li>
</ul>
</li>
</ul>
</ul>