title: using recursive function to populate an array with category and sub categories
body: <p>i store my categories and sub categories in the same table like this , each category or sub category may have it's own sub category </p>
  
  <pre><code>+--------+---------------+---------------+
  | id     | title         | parent        |
  +--------+---------------+---------------+
  |      1 | black         |             0 | 
  |      2 | red           |             0 | 
  |      3 | dark red      |             2 | 
  |      4 | light red     |             2 | 
  |      5 | very light red|             4 | 
  +--------+---------------+---------------+
  </code></pre>
  
  <p>i want to store all cat and sub categories in a array in a way that they keep their parent-child relation </p>
  
  <p>so i thought recursive functions are clean way to go so here is the best i came up with </p>
  
  <pre><code>function get_categories(){
  
      $array  =  array();
      $all    = $this-&gt;db-&gt;get('category' , array('parent'=&gt;0) ); 
     // this query gets all the parent categories ( select * where parent = 0 )
  
      foreach($all as $a )
      {
          $array[$a-&gt;id]['category'] =  $a-&gt;title ;
          $array[$a-&gt;id]['childs']   = $this-&gt;childs( $a-&gt;id );
      }
  
      echo '&lt;pre&gt;';print_r($array); echo '&lt;/pre&gt;';
  
  }
  
  
   // my recursive function
  function childs($parent_id = 0 , $arr = array()){
  
      $childs =  $this-&gt;db-&gt;get('category' , array('parent'=&gt;$parent_id ) );
      //  this query :  select * where parent = $parent_id 
  
      if($childs)
      {
        foreach($childs as $ch)
        {
           $arr[$ch-&gt;id][ 'category' ] = $ch-&gt;title;
           $arr[$ch-&gt;id][ 'childs' ] = $this-&gt;childs($ch-&gt;id , $arr );
        }
      }
  
  
      return $arr ;
  }
  </code></pre>
  
  <p>but i get lots of extra childs for each category even when there is no child  !
   here is the result in jsfiddle (An!!! :</p>
  
  <p><a href="http://jsfiddle.net/nkxgc4by/" rel="nofollow">http://jsfiddle.net/nkxgc4by/</a></p>