title: Recursive function for building array from tree
body: <p>I have an array that looks like this:</p>
  
  <pre><code>Array (
      [0] =&gt; Array
      (
          [term_id] =&gt; 23
          [name] =&gt; testasdf
          [depth] =&gt; 1
      )
      [1] =&gt; Array
      (
          [term_id] =&gt; 26
          [name] =&gt; asdf
          [depth] =&gt; 2
      )
      [2] =&gt; Array
      (
          [term_id] =&gt; 31
          [name] =&gt; Another level deep
          [depth] =&gt; 3
      )
      [3] =&gt; Array
      (
          [term_id] =&gt; 32
          [name] =&gt; Another level deep
          [depth] =&gt; 2
      )
      [4] =&gt; Array
      (
          [term_id] =&gt; 24
          [name] =&gt; testasdf
          [depth] =&gt; 1
      )
      [5] =&gt; Array
      (
          [term_id] =&gt; 27
          [name] =&gt; asdf
          [depth] =&gt; 1
      )
  )
  </code></pre>
  
  <p>Here is the recursive function that I'm using, it works except in some cases (where the depth is greater it seems.</p>
  
  <pre><code>function process(&amp;$arr, &amp;$prev_sub = null, $cur_depth = 1) {
      $cur_sub = array();
      while($line = current($arr)){
          if($line['depth'] &lt; $cur_depth){
              return $cur_sub; 
          }elseif($line['depth'] &gt; $cur_depth){
              $prev_sub = $this-&gt;process($arr, $cur_sub, $cur_depth + 1 );
          }else{
              $cur_sub[$line['term_id']] = array('term_id' =&gt; $line['term_id'], 'name' =&gt; $line['name']);
              $prev_sub =&amp; $cur_sub[$line['term_id']];
              next($arr);
          }
      }
      return $cur_sub;
  }
  </code></pre>
  
  <p>This is how the results look:</p>
  
  <pre><code>Array
  (
      [23] =&gt; Array
      (
          [26] =&gt; Array
          (
              [31] =&gt; Array
              (
                  [term_id] =&gt; 31
                  [name] =&gt; Another level deep
              )
          )
          [32] =&gt; Array
          (
              [term_id] =&gt; 32
              [name] =&gt; Another level deep
          )
      )
      [24] =&gt; Array
      (
          [term_id] =&gt; 24
          [name] =&gt; testasdf
      )
      [27] =&gt; Array
      (
          [term_id] =&gt; 27
          [name] =&gt; asdf
      )
  )
  </code></pre>
  
  <p>Any idea how I can have it so the term_id and name is shown for all depths?</p>