title: Build a tree from a flat array in codeigniter
body: <p>I've looked around the internet and haven't quite found what I'm looking for. I have a flat array with each element containing an 'id' and a 'parent_id'. Each element will only have ONE parent, but may have multiple children. If the parent_id = 0, it is considered a root level item. I'm trying to get my flat array into a tree. The samples I have found only working for core php. Because in codeigniter recursive is not qorking</p>
  
  <pre><code>function buildTree(array &amp;$elements, $parentId = 0) {
      $branch = array();
  
      foreach ($elements as $element) {
          if ($element['parent_id'] == $parentId) {
              $children = buildTree($elements, $element['id']);
              if ($children) {
                  $element['children'] = $children;
              }
              $branch[$element['id']] = $element;
              unset($elements[$element['id']]);
          }
      }
      return $branch;
  }
  </code></pre>
  
  <p>My Flat array is</p>
  
  <pre><code>Array
  (
      [1] =&gt; Array
          (
              [id] =&gt; 1
              [parent_id] =&gt; 0
              [permission_category] =&gt; Listing
  
      [3] =&gt; Array
          (
              [id] =&gt; 3
              [parent_id] =&gt; 1
              [permission_category] =&gt; Tour
          )
  
      [4] =&gt; Array
          (
              [id] =&gt; 4
              [parent_id] =&gt; 1
              [permission_category] =&gt; Activity
          )
  
      [12] =&gt; Array
          (
              [id] =&gt; 12
              [parent_id] =&gt; 0
              [permission_category] =&gt; Bookings
              [parent_permission_category] =&gt; 
          )
  
      [13] =&gt; Array
          (
              [id] =&gt; 13
              [parent_id] =&gt; 12
              [permission_category] =&gt; Activity Bookings
          )
  
      [14] =&gt; Array
          (
              [id] =&gt; 14
              [parent_id] =&gt; 12
              [permission_category] =&gt; Tour Bookings
          )
  
  );
  </code></pre>
  
  <p>It is only showing one parent children</p>
  
  <pre><code>Array
  (
      [1] =&gt; Array
          (
              [id] =&gt; 1
              [parent_id] =&gt; 0
              [permission_category] =&gt; Listing
              [children] =&gt; Array
                  (
  
                      [3] =&gt; Array
                          (
                              [id] =&gt; 3
                              [parent_id] =&gt; 1
                              [permission_category] =&gt; Tour
                          )
  
                      [4] =&gt; Array
                          (
                              [id] =&gt; 4
                              [parent_id] =&gt; 1
                              [permission_category] =&gt; Activity
                          )
                  )
  
          )
  
  )
  </code></pre>