Display Categories and subcategories using CodeIgniter Display Categories and subcategories using CodeIgniter codeigniter codeigniter

Display Categories and subcategories using CodeIgniter


This should work;

public function get_categories(){    $query = $this->db->get('Categories');    $return = array();    foreach ($query->result() as $category)    {        $return[$category->id] = $category;        $return[$category->id]->subs = $this->get_sub_categories($category->id); // Get the categories sub categories    }    return $return;}public function get_sub_categories($category_id){    $this->db->where('Category', $category_id);    $query = $this->db->get('Sub_Categories');    return $query->result();}

All this does is get's all the categories, but then gets all the subcategories for each of the categories. Calling the get_categories() function should return an object in the format you want.

I hope this helps.

Edit

You would call the get_categories function from your controller and pass it to the view;

$data['categories'] = $this->your_model->get_categories();$this->load->view('view_file', $data);

Then within your view you would display them like this;

<ul><?php     foreach ($categories as $category)        {?>    <li><?php echo $category->name; ?><?php    if(!empty($category->subs)) {         echo '<ul>';        foreach ($category->subs as $sub)  {            echo '<li>' . $sub->name . '</li>';        }        echo '</ul>';    }?></li><?php}?></ul>


Databaseimage for database tableTry thisin Model

public function getCategories(){    $query = $this->db->query('select * from categories where cat_parent=0');    return $query->result_array();}public function getCategoriesSub($parent){    $query = $this->db->query("select * from categories where cat_parent='$parent'");    return $query->result_array();}

in Controller

public function categories(){    $data['mcats'] = $this->admin_model->getCategories();    foreach($data['mcats'] as $key =>$val){        $subcats = $this->admin_model->getCategoriesSub($val['cid']);        if($subcats){            $data['scats'][$val['cid']] = $subcats;        }    }    $this->load->view('admin/header');    $this->load->view('admin/category_list', $data);    $this->load->view('admin/footer');}

In view

<ul><?php foreach ($mcats as $key =>$val)    {?><li><?php echo $val['cat_name']; ?><ul><?php    foreach ($scats[$val['cid']] as $sub)  {        echo '<li>' . $sub['cat_name'] . '</li>';    }?></ul></li><?php}?></ul>

its already working code - i think it is usefull