Note that there are some explanatory texts on larger screens.

plurals
  1. PONested lists using PHP's iterator?
    primarykey
    data
    text
    <p>I'm trying to display this kind of array:</p> <pre><code>$nodes = array( 1 =&gt; array( 'title' =&gt; 'NodeLvl1', 'children' =&gt; array(), ), 2 =&gt; array( 'title' =&gt; 'NodeLvl1', 'children' =&gt; array( 1 =&gt; array( 'title' =&gt; 'NodeLvl2', 'children' =&gt; array(), ), 2 =&gt; array( 'title' =&gt; 'NodeLvl2', 'children' =&gt; array( 1 =&gt; array( 'title' =&gt; 'NodeLvl3', 'children' =&gt; array(), ), 2 =&gt; array( 'title' =&gt; 'NodeLvl3', 'children' =&gt; array(), ), ), ), ), ), 3 =&gt; array( 'title' =&gt; 'NodeLvl1', 'children' =&gt; array(), ), ); </code></pre> <p>like this:</p> <pre><code>&lt;ul&gt; &lt;li&gt; NodeLvl1 &lt;/li&gt; &lt;li&gt; NodeLvl1 &lt;ul&gt; &lt;li&gt;NodeLv2&lt;/li&gt; ... &lt;/ul&gt; &lt;/li&gt; ... </code></pre> <p>Basically a nested list taking into account the "children" property. So far I've come up with this:</p> <pre><code>class It extends RecursiveIteratorIterator{ protected $tab = "\t"; public function beginChildren(){ if(count($this-&gt;getInnerIterator()) == 0) return; echo str_repeat($this-&gt;tab, $this-&gt;getDepth())."&lt;ul&gt;\n"; } public function endChildren(){ if(count($this-&gt;getInnerIterator()) == 0) return; echo str_repeat($this-&gt;tab, $this-&gt;getDepth())."\n&lt;/ul&gt;"; } public function nextElement(){ echo str_repeat($this-&gt;tab, $this-&gt;getDepth() + 1).'&lt;li&gt;'; } } $it = new It(new RecursiveArrayIterator($nodes)); foreach($it as $key =&gt; $item) echo $item; </code></pre> <p>Which doesn't work quite right: I get each item wrapped between <code>&lt;ul&gt;</code>s and I don't know how can I close <code>&lt;li&gt;</code>s...</p> <p>Any ideas on how to make this work? Also is it possible to get all the array properties (the actual element), instead of just the "title" property inside my foreach() loop? And can this be done with objects instead of arrays?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload