user6724476
user6724476

Reputation:

Show and list data base on each category from database with codeigniter

i'm trying to show and list data base on each category from database with codeigniter.

Table structure:

Category: id_cat, name_cat

Subcategory: id_subcat, id_cat, name_subcat

I want the output like this:

  1. Car
    • Lamborghini
    • Ford
    • Nissan
  2. Bike
    • Honda
    • Yamaha
  3. Airplane
    • Boeing

But, when i run my code it show like this:

  1. Car
    • Lamborghini
    • Ford
    • Nissan
  2. Bike
    • Lamborghini
    • Ford
    • Nissan
  3. Airplane
    • Lamborghini
    • Ford
    • Nissan

My code:

Controller

$this->data['get_category'] = $this->Category_model->get_all_sidebar();
$this->data['get_subcat'] = $this->Subcategory_model->get_all_sidebar();
$this->load->view('front/body', $this->data);

Model

Category:

public function get_all_sidebar()
{
  return $this->db->get($this->table)->result();
}  

Subcategory:

public function get_all_sidebar()
{
  $this->db->select('*');
  $this->db->join('category', 'category.id_cat = subcategory.id_cat');
  $this->db->order_by('id_subcat', 'ASC');
  return $this->db->get('subcategory')->result();
}  

View

<?php
echo '<ul class="category">';
foreach($get_category as $category)
{
  echo "<li>$category->name_cat</li>";

  echo "<ul>";
  foreach($get_subcat as $subcat)
  {
    echo "<li>$subcat->name_subcat</li>";
  }
    echo "</ul>";

}
echo "</ul>";
?>

Any help will be so appreciate, thank you

Upvotes: 0

Views: 2189

Answers (1)

Amarjeet Chahal
Amarjeet Chahal

Reputation: 270

Try this one

public function get_categories() {
    $query = $this->db->get('category');
    $return = array();
    foreach ($query->result() as $category) {
        $return[$category->id_cat] = $category;
        $return[$category->id_cat]->subs = $this->get_sub_categories($category->id_cat);
    } return $return;
}

public function get_sub_categories($category_id) {
    $this->db->where('id_cat', $category_id);
    $query = $this->db->get('subcategory');
    return $query->result();
}

Then in your controller

$data['categories'] = $this->Category_model->get_categories();
$this->load->view('front/body', $data);

And use in view like this

<ul class="category">
    <?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>

Upvotes: 1

Related Questions