1

我有一个 Joomla 1.5 网站。我的网站上有不同“状态”的文章。我要做的是“计数”并显示有多少文章,例如“status = 1”(过期)或“status = 3”(阻塞)或“status = 2”(活动)等。

这是 PhpMyAdmin 中的状态 - http://awesomescreenshot.com/07a8ijz75

这是我写的,但它总是给我相同的结果 - 1

<?php echo count($this->row->status==1) ?>

我错过了什么?谢谢

4

2 回答 2

11

使用 SQL 计数函数。

select count(*) from articles where status = 1;

使用您的数据库!如果您在 PHP 代码中对数据库中的数据进行排序、计数等操作,那么您做错了

如果您想要所有状态,请执行以下操作:

select status, count(*) from articles group by status;
于 2012-06-20T14:23:30.223 回答
1

PHP 中的 count 函数对数组中的所有元素进行计数,在您的示例中,您向其传递了一个布尔值。结果 count 不知道如何处理它,因此它返回 -1,这不是有效的计数。

我的 PHP 真的很生疏(我很久没有使用它了),但是这里有两种可能的方法来完成你想要的:

1. 使用函数 map/reduce 风格

<?php
$row[0]->status = 1;
$row[1]->status = 2;
$row[2]->status = 1;
$row[3]->status = 3;
$row[4]->status = 1;

// Count the number of statuses that are equal to 1
echo array_reduce(array_map(function($x) {
    return $x->status == 1 ? 1: 0;
}, $row), function($x, $y) {return $x + $y;});

显然,您必须用 $this->row 替换 $row 变量。该代码基本上分两步工作。内部部分:

array_map(function($x) {
    return $x->status == 1 ? 1: 0;
}, $row)

创建一个列表,其中每个等于 1 的状态都变为 1,而其他所有状态都变为 0。因此,您有一个“array(1, 0, 1, 0, 1)”数组。代码的输出部分:

array_reduce( ... , function($x, $y) {return $x + $y;});

将新数组作为第一个参数,并通过将数组的前两个值传递给函数,然后将每个后面的值和最后一次函数调用的结果进行汇总。结果,所有值都被求和,并且您对匹配值有适当的计数。

2.使用简单的程序风格

<?php
$row[0]->status = 1;
$row[1]->status = 2;
$row[2]->status = 1;
$row[3]->status = 3;
$row[4]->status = 1;

// Do it again, but in a procedural style
$num_1_statuses = 0;
foreach ($row as $r) {
    if ($r->status == 1) {
        $num_1_statuses++;
    }
}
echo $num_1_statuses;

这应该非常简单,它只有一个变量,只要一行的状态匹配,它就会递增。

于 2012-06-20T15:19:58.483 回答