如何使用 Codeigniter 对组中的项目进行计数?
我正在使用活动记录返回日期分组列表,代码如下:
function get_archive_links(){
$this->db->order_by('date','desc');
$this->db->group_by('MONTH(date), YEAR(date)');
$query = $this->db->get('blog');
foreach ($query->result() as $row) {
$data[] = array(
'id' => $row->id,
'date' => $row->date
);
}
return $data;
}
在我的页面上循环和回显时返回:
- 2012 年 2 月
- 2012 年 1 月
- 2012 年 12 月
如何计算组中的每个项目并将其显示在我的列表中?示例:
- 2012 年 2 月 (2)
- 2012 年 1 月 (6)
- 2012 年 12 月 (7)
我将计算每个月有多少博客文章。
I am using active record to return a grouped list of dates with the following code:
function get_archive_links(){
$this->db->order_by('date','desc');
$this->db->group_by('MONTH(date), YEAR(date)');
$query = $this->db->get('blog');
foreach ($query->result() as $row) {
$data[] = array(
'id' => $row->id,
'date' => $row->date
);
}
return $data;
}
Which when looped and echoed on my page returns:
- Febuary 2012
- January 2012
- December 2012
How can I count each item in the group and display it in my list? Example:
- Febuary 2012 (2)
- January 2012 (6)
- December 2012 (7)
I will be counting how many blog posts there where for each month.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要删除
GROUP BY
然后在 PHP 中进行计数,或者将->select('COUNT(id) AS num_posts')
添加到您的 AR 查询中。我可能会添加->select()
,因为它的工作量更少:)You need to either remove the
GROUP BY
then count in PHP, or add a->select('COUNT(id) AS num_posts')
to your AR query. I'd probably add the->select()
, as it's less work :)你可以用sql count函数来实现。如果您使用分组依据,则计数函数返回行组的计数行。
像这样,
}
You can it with sql count function. if you are using group by, count function returning count rows for row group.
like this,
}
这很完美,但如果不存在类别帖子,则不会显示零计数,
这是我的功能,
This works perfect but not shows zero counts if not exist post for category
here is my function,
我已经找到了零计数问题的答案。
I've got the answer for the zero count issue.