Codeigniter - 在foreaching中通过id从另一个表获取行计数

时间:2017-12-08 20:22:27

标签: php mysql codeigniter mysqli

我有分类控制器 - 索引

public function index()
    {

        $query = $this->db->query("SELECT * FROM categories ORDER BY priority");
        $this->_viewdata['categories'] = $query->result();
        //-- I will use model for mysql queries!

        $this->load->view('admin/categories', $this->_viewdata);
    }

在视图中使用foreach打印结果:

<?php
    foreach ($categories as $category) {
?>
       Name: <?=$category->name;?> // and etc...
       Subcategories: // <- I want to get subcats count for every category by its id (where catid='$category->id') like this
    <?php
    }
    ?>

我有一个名为“子类别”的表,我在其中有“catid”列。我想让每个子类别按类别计算并在视图中显示。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

就像我在评论中所说的那样,我会做的是加入表格,如:

SELECT * FROM categories c JOIN subcategories s ON s.catid = c.id ORDER BY c.priority

或者,因为您使用的是Codeigniter,您甚至可以使用:

$this->db->join('subcategories', 'subcategories.catid = categories.id');

然后我将子序列保存到不同的数组并迭代这些。

<?php
    $newCategories;
    foreach ($categories as $category) {
      if($category->name != $cat){
       //New category
       $cat = $category->name;
       $newCategories[$cat][] = $category;
      }
      else{
       $newCategories[$cat][] = $category;
      }
    }
    foreach($newCategories as $name => $cat){
?>
       Name: <?php echo $name ?>.
       Subcategories: <?php 
                       foreach($cat as $sub){
                        echo $sub->..; //Fill in your template
                       }
                      ?>

我确信它可以做得更好。