Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This recursive function will add the given datum to the correct parent, and should be called once for each element in your starting array.</p> <pre><code>function add_branch(&amp;$tree, $datum, $parent) { // First we have the base cases: // If the parent is NULL then we don't need to look for the parent if ($parent == NULL) { $tree[$datum] = array(); return true; } // If the array we've been given is empty, we return false, no parent found in this branch if (! count($tree)) { return false; } // We loop through each element at this level of the tree... foreach($tree as $key =&gt; $val) { // If we find the parent datum... if ($key == $parent) { // We add the new array in and we're done. $tree[$key][$datum] = array(); return true; } // Otherwise, check all the child arrays else { // Now we check to see if the parent can be found in the curent branch // If a recursive call found a parent, we're done if (add_branch($tree[$key], $datum, $parent)) { return true; } } } // If none of the recursive calls found the parent, there's no match in this branch return false; } </code></pre> <p>The comments are quite verbose, in the hope that you can understand what is going on. I'd encourage you to do a bit of reading on recursive functions to get your head around it.</p> <p>This is how it would be used:</p> <pre><code>$arr = array( 0 =&gt; NULL, 1 =&gt; NULL, 2 =&gt; NULL, 3 =&gt; NULL, 8 =&gt; '2', 9 =&gt; '2', 10 =&gt; '2', 11 =&gt; '2', 12 =&gt; '3', 13 =&gt; '3', 14 =&gt; '8', 15 =&gt; '8', 16 =&gt; '14', 17 =&gt; '14', 18 =&gt; '14' ); $final = array(); foreach ($arr as $datum =&gt; $parent) { add_branch($final, $datum, $parent); } </code></pre> <p><code>$final</code> now has the correct finishing array, as indicated in the question.</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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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