using recursive function to populate an array with category and sub categories
18:59 12 Jan 2015

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

+--------+---------------+---------------+
| id     | title         | parent        |
+--------+---------------+---------------+
|      1 | black         |             0 | 
|      2 | red           |             0 | 
|      3 | dark red      |             2 | 
|      4 | light red     |             2 | 
|      5 | very light red|             4 | 
+--------+---------------+---------------+

i want to store all cat and sub categories in a array in a way that they keep their parent-child relation

so i thought recursive functions are clean way to go so here is the best i came up with

function get_categories(){

    $array  =  array();
    $all    = $this->db->get('category' , array('parent'=>0) ); 
   // this query gets all the parent categories ( select * where parent = 0 )

    foreach($all as $a )
    {
        $array[$a->id]['category'] =  $a->title ;
        $array[$a->id]['childs']   = $this->childs( $a->id );
    }

    echo '
';print_r($array); echo '
'; } // my recursive function function childs($parent_id = 0 , $arr = array()){ $childs = $this->db->get('category' , array('parent'=>$parent_id ) ); // this query : select * where parent = $parent_id if($childs) { foreach($childs as $ch) { $arr[$ch->id][ 'category' ] = $ch->title; $arr[$ch->id][ 'childs' ] = $this->childs($ch->id , $arr ); } } return $arr ; }

but i get lots of extra childs for each category even when there is no child ! here is the result in jsfiddle (An!!! :

http://jsfiddle.net/nkxgc4by/

php codeigniter recursion