title: PHP Traversing Function to turn single array into nested array with children - based on parent id
body: <p>I have an array similar to this:</p>
  
  <pre><code>Array
  (
      Array
      (
          [ID] =&gt; 1
          [parentcat_ID] =&gt; 0
      ),
      Array
      (
          [ID] =&gt; 2
          [parentcat_ID] =&gt; 0
      ),
      Array
      (
          [ID] =&gt; 6
          [parentcat_ID] =&gt; 1
      ),
      Array
      (
          [ID] =&gt; 7
          [parentcat_ID] =&gt; 1
      ),
      Array
      (
          [ID] =&gt; 8
          [parentcat_ID] =&gt; 6
      ),
      Array
      (
          [ID] =&gt; 9
          [parentcat_ID] =&gt; 1
      ),
      Array
      (
          [ID] =&gt; 13
          [parentcat_ID] =&gt; 7
      ),
      Array
      (
          [ID] =&gt; 14
          [parentcat_ID] =&gt; 8
      )
  
  )
  </code></pre>
  
  <p>But I need a function to recursively put each item into a 'children' array inside the relevant parent array. So it would look more like this:</p>
  
  <pre><code>Array
  (
      Array
      (
          [ID] =&gt; 1
          [parentcat_ID] =&gt; 0
          [children] =&gt; Array (
              Array
              (
                  [ID] =&gt; 6
                  [parentcat_ID] =&gt; 1
                  [childen] =&gt; Array (
                      Array
                      (
                          [ID] =&gt; 8
                          [parentcat_ID] =&gt; 6
                          [children] =&gt; Array (
                               Array
                               (
                                   [ID] =&gt; 14
                                   [parentcat_ID] =&gt; 8
                               )
                          )
                      )
                  )
              ),
              Array
              (
                  [ID] =&gt; 7
                  [parentcat_ID] =&gt; 1
                  [children] =&gt; Array(
                       Array
                       (
                           [ID] =&gt; 13
                           [parentcat_ID] =&gt; 7
                       )
                  ) 
              ),
              Array
              (
                  [ID] =&gt; 9
                  [parentcat_ID] =&gt; 1
              )
  
          )
      )
      Array
      (
          [ID] =&gt; 2
          [parentcat_ID] =&gt; 0
  
      )
  
  )
  </code></pre>
  
  <p>I hope that makes sense!</p>