title: PHP: Recursive array function
body: <p>I want to create a function that returns the full path from a set node, back to the root value. I tried to make a recursive function, but ran out of luck totally. What would be an appropriate way to do this? I assume that a recursive function is the only way?</p>
  
  <p>Here's the array:</p>
  
  <pre><code>Array
  (
      [0] =&gt; Array
          (
              [id] =&gt; 1
              [name] =&gt; Root category
              [_parent] =&gt; 
          )
  
      [1] =&gt; Array
          (
              [id] =&gt; 2
              [name] =&gt; Category 2
              [_parent] =&gt; 1
          )
  
      [2] =&gt; Array
          (
              [id] =&gt; 3
              [name] =&gt; Category 3
              [_parent] =&gt; 1
          )
  
      [3] =&gt; Array
          (
              [id] =&gt; 4
              [name] =&gt; Category 4
              [_parent] =&gt; 3
          )
  )
  </code></pre>
  
  <p>The result I want my function to output when getting full path of node id#4:</p>
  
  <pre><code>Array
  (
      [0] =&gt; Array
          (
              [id] =&gt; 1
              [name] =&gt; Root category
              [_parent] =&gt; 
          )
  
      [1] =&gt; Array
          (
              [id] =&gt; 3
              [name] =&gt; Category 3
              [_parent] =&gt; 1
          )
  
      [2] =&gt; Array
          (
              [id] =&gt; 4
              [name] =&gt; Category 4
              [_parent] =&gt; 3
          )
  )
  </code></pre>
  
  <p>The notoriously bad example of my recursive skills:</p>
  
  <pre><code>    function recursive ($id, $array) {
  
          $innerarray = array();
          foreach ($array as $k =&gt; $v) {
  
              if ($v['id'] === $id) {
                  if ($v['_parent'] !== '') {
                      $innerarray[] = $v;
                      recursive($v['id'], $array);
                  }
              }
  
          }
          return $innerarray; 
      }
  </code></pre>