Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This requires a very basic recursive function to parse the child/parent pairs to a tree structure and another recursive function to print it out. Only one function would suffice but here's two for clarity (a combined function can be found at the end of this answer).</p> <p>First initialize the array of child/parent pairs:</p> <pre><code>$tree = array( 'H' =&gt; 'G', 'F' =&gt; 'G', 'G' =&gt; 'D', 'E' =&gt; 'D', 'A' =&gt; 'E', 'B' =&gt; 'C', 'C' =&gt; 'E', 'D' =&gt; null ); </code></pre> <p>Then the function that parses that array into a hierarchical tree structure:</p> <pre><code>function parseTree($tree, $root = null) { $return = array(); # Traverse the tree and search for direct children of the root foreach($tree as $child =&gt; $parent) { # A direct child is found if($parent == $root) { # Remove item from tree (we don't need to traverse this again) unset($tree[$child]); # Append the child into result array and parse its children $return[] = array( 'name' =&gt; $child, 'children' =&gt; parseTree($tree, $child) ); } } return empty($return) ? null : $return; } </code></pre> <p>And a function that traverses that tree to print out an unordered list:</p> <pre><code>function printTree($tree) { if(!is_null($tree) &amp;&amp; count($tree) &gt; 0) { echo '&lt;ul&gt;'; foreach($tree as $node) { echo '&lt;li&gt;'.$node['name']; printTree($node['children']); echo '&lt;/li&gt;'; } echo '&lt;/ul&gt;'; } } </code></pre> <p>And the actual usage:</p> <pre><code>$result = parseTree($tree); printTree($result); </code></pre> <p>Here's the contents of <code>$result</code>:</p> <pre><code>Array( [0] =&gt; Array( [name] =&gt; D [children] =&gt; Array( [0] =&gt; Array( [name] =&gt; G [children] =&gt; Array( [0] =&gt; Array( [name] =&gt; H [children] =&gt; NULL ) [1] =&gt; Array( [name] =&gt; F [children] =&gt; NULL ) ) ) [1] =&gt; Array( [name] =&gt; E [children] =&gt; Array( [0] =&gt; Array( [name] =&gt; A [children] =&gt; NULL ) [1] =&gt; Array( [name] =&gt; C [children] =&gt; Array( [0] =&gt; Array( [name] =&gt; B [children] =&gt; NULL ) ) ) ) ) ) ) ) </code></pre> <hr> <p>If you want a bit more efficiency, you can combine those functions into one and reduce the number of iterations made:</p> <pre><code>function parseAndPrintTree($root, $tree) { $return = array(); if(!is_null($tree) &amp;&amp; count($tree) &gt; 0) { echo '&lt;ul&gt;'; foreach($tree as $child =&gt; $parent) { if($parent == $root) { unset($tree[$child]); echo '&lt;li&gt;'.$child; parseAndPrintTree($child, $tree); echo '&lt;/li&gt;'; } } echo '&lt;/ul&gt;'; } } </code></pre> <p>You'll only save 8 iterations on a dataset as small as this but on bigger sets it could make a difference.</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