title: Looping through an array with children of children
body: <p>I am trying to make and save a tree of items where one item can be a child of another. But this child can also have children etc etc. So for instance I am getting an array like:</p>
  
  <pre><code>array(
      [0] array(
          'id' =&gt; 100
      ),
      [1] array(
          'id' =&gt; 101,
          'children' =&gt; array(
              [0] array(
                  'id' =&gt; 103
              )
          )
      )
  )
  </code></pre>
  
  <p>Or as JSON:</p>
  
  <pre><code>[{"id":1},{"id":3,"children":[{"id":4},{"id":5},{"id":6}]},{"id":2},{"id":7,"children":[{"id":8},{"id":9}]},{"id":10,"children":[{"id":11},{"id":12}]}][{"id":1},{"id":3,"children":[{"id":4},{"id":5},{"id":6}]},{"id":2},{"id":7,"children":[{"id":8},{"id":9}]},{"id":10,"children":[{"id":11},{"id":12}]}]
  </code></pre>
  
  <p>With below code I can go one level deep to find children and perform an action. Of course I can add another if has children, but that would mean a whole lot of if and foreach statements to get to a bottom of the array. Especially as I know sometimes children can go like 10 levels deep in practice.</p>
  
  <pre><code>public function sortPages(Request $request) {
      $data = json_decode($request-&gt;data);
      foreach($data as $sort=&gt;$id) {
          $this-&gt;saveSortingOrder($id-&gt;id, $sort);
          if(isset($id-&gt;children)) {
              foreach($id-&gt;children as $sort_next=&gt;$id_next) {
                  $this-&gt;saveSortingOrder($id_next-&gt;id, $sort_next);
                  $this-&gt;setParent($id_next-&gt;id, $id-&gt;id);
              }
          }
      }
  }
  </code></pre>
  
  <p>Is there an easy way to get the job done?</p>
  
  <p>Fixed it using below code:</p>
  
  <pre><code>public function sortPages(Request $request) {
      $data = json_decode($request-&gt;data);
      foreach($data as $sort_value=&gt;$id) {
          $this-&gt;saveSortingOrder($id-&gt;id, $sort_value);
          if(isset($request-&gt;parent)) {
              $this-&gt;setParent($id-&gt;id, $request-&gt;parent);
          }
          if(isset($id-&gt;children)) {
              $new_request = new Request;
              $new_request-&gt;data = json_encode($id-&gt;children);
              $new_request-&gt;parent = $id-&gt;id;
              $this-&gt;sortPages($new_request);
          }
      }
  }
  </code></pre>