title: Organising a page tree using PHP foreach
body: <p>I'm relatively inexperienced with PHP. Basically, I have some page data which looks like this:</p>
  
  <p><a href="https://i.stack.imgur.com/mxF1F.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mxF1F.jpg" alt="Data"></a></p>
  
  <p>I'm looking to use <code>foreach</code> loops to organise child pages into a Subpages array, which will be a property of the parent page. Below is what I have written so far, which only has partial success. I was wondering if I'm along the right lines or if their is a much more efficient way of doing this using a library or a better logic. Any help would be appreciated!</p>
  
  <p>PHP ($nav is the data is shown in the image about)</p>
  
  <pre><code>function renderNav($nav){
  
      $data = $nav;
  
      foreach ($data as &amp;$page) {
          $page['Subpages'] = array_filter($data, function($i) use ($page){ return $i['ParentId'] == $page['Id']; });
          if(sizeof($page['Subpages'])==0){
              $page['Subpages'] = array();
          };
          usort($page['Subpages'], function($a, $b){ return $a['Order'] - $b['Order']; });
      };
  
      $filtered = array();
      foreach ($data as &amp;$page) {
          if($page['ParentId'] == 0 || $page['ParentId'] == null){
              array_push($filtered, $page);
          }
      };
  }
  </code></pre>