Q:

Subcategory inside category in the Codeigniter framework

I want to show subcategory inside the main category.  My table looks like this.  but when i print_r($cat_id) it returns only the last id of the category.  How can I fix this?  Here is my controller: 
$data['categories'] = $this->courses_model->get_all_categories_for_courses();

            foreach($data['categories'] as $ct){

                        $cat_id = $ct['id'];        
                }

            $data['subcategories'] = $this->courses_model->get_all_subcategories_for_courses($cat_id);

            $this->load->view('templates/header');
            $this->load->view('courses/courses-grid-fullwidth', $data);
            $this->load->view('templates/footer');
        }

and here is my model: 
public function get_all_categories_for_courses() {
        $query = $this->db->get_where('categories', array('parent_id' => NULL));
        return $query->result_array();
    }

    function get_all_subcategories_for_courses($cat_id) {
        $query = $this->db->get_where('categories', array('parent_id' => $cat_id));
        return $query->result_array();
    } 

and here is my view page: 
<? php foreach($categories as $cat): ? >
          <div class="col-md-3 col-sm-6 incat">

             <h4>
               <a href="#" class="catname"><i class="fa <? = $cat['icon']; ? >" aria-hidden="true"></i>
               <? = $cat['name_rus']; ? ></a>               
             </h4>

            <ul>
              <? php foreach($subcategories as $subcat): ? >
              <li><a href="#"><?= $subcat['name_rus']; ? ></a></li>
              <? php endforeach; ? >
            </ul>
          </div>
        <? php endforeach; ? >

Thanks in advance! 

A:

Or you can do this
<? php foreach($categories as $cat): ? >
          <div class="col-md-3 col-sm-6 incat">

             <h4>
               <a href="<?= site_url('/courses/category/'.$cat['category_slug']); ? >" class="catname"><i class="fa <? = $cat['icon']; ? >" aria-hidden="true"></i>
               <? = $cat['name_rus']; ? ></a>               
             </h4>

            <ul>
            <? php 
            $query = $this->db->get_where('categories', array('parent_id' => $cat['id']));
            ? >

              <? php foreach($query->result() as $subcat): ? >
              <li><a href="<?= site_url('/courses/category/'.$subcat->category_slug); ? >"><? = $subcat->name_rus; ? ></a></li>
              <? php endforeach; ? >
            </ul>
          </div>
        <? php endforeach; ? >

