Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You should use recursion.</p> <p>Here an exemple of code:</p> <pre><code>$datas = array( array('id' =&gt; 1, 'parent' =&gt; 0, 'name' =&gt; 'Page 1'), array('id' =&gt; 2, 'parent' =&gt; 1, 'name' =&gt; 'Page 1.1'), array('id' =&gt; 3, 'parent' =&gt; 2, 'name' =&gt; 'Page 1.1.1'), array('id' =&gt; 4, 'parent' =&gt; 3, 'name' =&gt; 'Page 1.1.1.1'), array('id' =&gt; 5, 'parent' =&gt; 3, 'name' =&gt; 'Page 1.1.1.2'), array('id' =&gt; 6, 'parent' =&gt; 1, 'name' =&gt; 'Page 1.2'), array('id' =&gt; 7, 'parent' =&gt; 6, 'name' =&gt; 'Page 1.2.1'), array('id' =&gt; 8, 'parent' =&gt; 0, 'name' =&gt; 'Page 2'), array('id' =&gt; 9, 'parent' =&gt; 0, 'name' =&gt; 'Page 3'), array('id' =&gt; 10, 'parent' =&gt; 9, 'name' =&gt; 'Page 3.1'), array('id' =&gt; 11, 'parent' =&gt; 9, 'name' =&gt; 'Page 3.2'), array('id' =&gt; 12, 'parent' =&gt; 11, 'name' =&gt; 'Page 3.2.1'), ); function generatePageTree($datas, $parent = 0, $depth=0){ $ni=count($datas); if($ni === 0 || $depth &gt; 1000) return ''; // Make sure not to have an endless recursion $tree = '&lt;ul&gt;'; for($i=0; $i &lt; $ni; $i++){ if($datas[$i]['parent'] == $parent){ $tree .= '&lt;li&gt;'; $tree .= $datas[$i]['name']; $tree .= generatePageTree($datas, $datas[$i]['id'], $depth+1); $tree .= '&lt;/li&gt;'; } } $tree .= '&lt;/ul&gt;'; return $tree; } echo(generatePageTree($datas)); </code></pre> <p>You can test it at: <a href="http://phpfiddle.org/main/code/1qy-5fj" rel="nofollow noreferrer">http://phpfiddle.org/main/code/1qy-5fj</a></p> <p>Or if you want the exact format:</p> <pre><code>function generatePageTree($datas, $parent = 0, $depth = 0){ $ni=count($datas); if($ni === 0 || $depth &gt; 1000) return ''; // Make sure not to have an endless recursion $tree = ''; for($i=0; $i &lt; $ni; $i++){ if($datas[$i]['parent'] == $parent){ $tree .= str_repeat('-', $depth); $tree .= $datas[$i]['name'] . '&lt;br/&gt;'; $tree .= generatePageTree($datas, $datas[$i]['id'], $depth+1); } } return $tree; } </code></pre> <p>The test: <a href="http://phpfiddle.org/main/code/jw3-s1j" rel="nofollow noreferrer">http://phpfiddle.org/main/code/jw3-s1j</a></p>
 

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