title: Specific algorithm to recurse through a tree structure in PHP
body: <p>In PHP, I have a structure like this:</p>
  
  <pre><code>Array
  (
      [0] = Array
      (
          'id' =&gt; 1,
          'parent' =&gt; 0
      )
  
      [1] = Array
      (
          'id' =&gt; 2,
          'parent' =&gt; 1
      )
  
      [2] = Array
      (
          'id' =&gt; 3,
          'parent' =&gt; 1
      )
  
      [3] = Array
      (
          'id' =&gt; 4,
          'parent' =&gt; 2
      )
  )
  </code></pre>
  
  <p>The <code>id</code> is a unique integer and the <code>parent</code> is a reference to another element's <code>id</code>. If <code>parent</code> is 0, then it has no parent. The tree structure looks like this:</p>
  
  <pre><code>1 -&gt; 2 -&gt; 4
    -&gt; 3
  </code></pre>
  
  <p>(I hope that is clear!). I have been trying to determine an algorithm that will produce a nested array or similar output that exposes the tree hierarchy so I can work with it; for instance one such output would be: <code>tree = ['1' =&gt; ['2' =&gt; ['4'], '3']]]</code>. The algorithm could support an array of any arbitrary depth; but I am limiting it on the proviso that a child cannot have more than one parent.</p>
  
  <p>Apologies for the non-standard syntax, I hope it effectively communicates what I'm trying to achieve, which is a depth-first search, I think - however the implementations I've come across are too dry for my understand so I'd appreciate some help with this.</p>