我的数组如下。我要做的是计算数组中read_status为null或"new"的节点数。
有什么比在数组中循环更充分的东西吗?
Array
(
[0] => Array
(
[id] => 428
[read_status] =>
)
[1] => Array
(
[id] => 427
[read_status] =>
)
[2] => Array
(
[id] => 441
[read_status] => new
)
[3] => Array
(
[id] => 341
[read_status] => read
)
)
所以计数应该是3。
您可以进行
$count = count(array_filter($myArray, function($item){
return $item['read_status'] != 'new';
}));
echo $count;
但我认为这样循环更有效:
$count = 0;
foreach($myArray as $item){
if($item['read_status'] != 'new')$count++;
}
echo $count;
在数组中进行循环并没有错,它实际上可能比使用通用方法更快。很简单:
$count = 0;
foreach ($arrays as $entry)
{
if (!$entry['read_status'] || $entry['read_status'] === "new")
{
$count++;
}
}
echo $count;
实际上,我通过完全删除null改进了SQL,所以现在read_status要么是read,要么是new。
IF(feed_read.read_status IS NULL,'new','read') AS read_status
从那里,我可以利用另一个SO问题来计算"新"元素。
$counted = array_count_values(array_map(function($value){return $value['read_status'];}, $result));
echo $counted['new'];