获取类别和子类别Codeigniter

时间:2013-12-24 16:49:13

标签: php codeigniter

我从同一个表中获取子类别时遇到问题,子类别有一个表示主要类别的parentid。

我哪里错了?

我的结构是下一个。

控制器:

$cats = $this->categories_model->getCategories();
     foreach($cats as $ct){
         $cat_id = $ct->id;
     }
$data['categories'] = $this->categories_model->getCategories();
$data['subcategories'] = $this->categories_model->getSubcategories($cat_id);

型号:

public function getCategories() {

        $query = $this->db->get_where('categories', array('visible' => 1, 'parentid' => 0));
        return $query->result();
    }
    function getSubcategories($cat_id) {
        $this->db->select('*');
        $this->db->from('categories');
        $this->db->where(array('parentid' => $cat_id, 'visible' => 1));
        $query = $this->db->get();
        return $query->result();
    } 

查看:

<h4>Categories</h4>
          <div class="list-group categories">
          <?php foreach($categories as $category): ?>
            <a href="<?php echo site_url() . '/products/catalog_list/' . $category->id ; ?>" class="list-group-item"><?php echo $category->name ; ?><span class="glyphicon glyphicon-chevron-right"></span></a>
            <?php foreach($subcategories as $subcategory): ?>
            <div class="list-subgroups">
              <a href="<?php echo $subcategory->id; ?>" class="list-subgroup-item"><?php echo $subcategory->name; ?></a>
            </div>
            <?php endforeach; ?>
            <?php endforeach; ?>
          </div>

表格数据:

id  parentid    name    description metatags    visible 
1   0   Boots   Boots   boots   1
2   1   Man boots   man boots   NULL    1
3   1   Women boots women boots NULL    1
5   0   Jackets Jackets NULL    1
6   5   Women jackets   Women jackets   NULL    1

1 个答案:

答案 0 :(得分:1)

我认为你的控制器出了问题。你目前有

$cats = $this->categories_model->getCategories();
    foreach($cats as $ct){
        $cat_id = $ct->id;
    }
$data['categories'] = $this->categories_model->getCategories();
$data['subcategories'] = $this->categories_model->getSubcategories($cat_id);

您正在$cat_id循环中分配foreach并且不执行任何操作。您只使用最后一个类别ID来选择子类别。

您将需要重新排列代码,以便获取当前类别的所有子类别。

这可能只需要将您的子类别选择代码放入循环中,因为您每次都会覆盖您的变量,具有类似的效果。