我知道PHP的函数count()
,但是有没有一种函数可以计算一个值在数组中出现的次数呢?
例如:
$array = array(
[0] => 'Test',
[1] => 'Tutorial',
[2] => 'Video',
[3] => 'Test',
[4] => 'Test'
);
现在我想要计算“Test”出现的次数。
PHP有一个名为array_count_values
的函数可以实现此功能。
示例:
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
输出:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
array_count_values
,您可以在此处的文档中找到有关该函数的更多信息:http://www.php.net/manual/en/function.array-count-values.php
以下是该页面上的示例:<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
将会产生:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
{{ $comment->count(['comment']) }}
只返回了comments
列中的所有值。我希望计算每篇文章有多少评论。在commentable_id
列中存储了来自文章的id。正如您所想象的那样,随着文章获得更多评论,id会重复。 - Eduardo