【问题标题】:Codeigniter - in view while foreach-ing get row count from another table by idCodeigniter - 在 foreach-ing 时通过 id 从另一个表中获取行数
【发布时间】:2018-05-23 03:05:00
【问题描述】:

我有类别控制器 - 索引

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”列。我想按类别获取每个子类别计数并将其显示在视图中。我该怎么做?

【问题讨论】:

  • 您必须将子类别加入到您的 sql 语句中。 SELECT * FROM categories c JOIN subcategories s ON s.catid = c.id ORDER BY c.priority
  • 当我使用这个查询时,我怎样才能分别获得 subcats ->count 和 categories ->result?
  • @NurlanXp,你应该问自己“哦,当我这样做时,我会得到什么?我知道,我会在 $this->_viewdata['categories'] 和看看结果如何。”甚至在 phpmyadmin 中运行 SQL 并从那里检查结果...
  • 确实,在你尝试之前不要敲它。这就是故障排除...尝试和失败,看看你需要什么和你得到什么

标签: php mysql codeigniter mysqli


【解决方案1】:

就像我在 cmets 中所说的那样,我会加入如下表:

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');

然后我会将 subcats 保存到不同的数组并遍历它们。

<?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
                       }
                      ?>

我相信它可以做得更好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多