可能重复:
How to find the repeating elements in an array?PHP - 多少次
如果我有这样的阵列:阵列( “哎”, “测试”, “哎”);
我想统计我有多少次“嘿”这个词,我该怎么做?
可能重复:
How to find the repeating elements in an array?PHP - 多少次
如果我有这样的阵列:阵列( “哎”, “测试”, “哎”);
我想统计我有多少次“嘿”这个词,我该怎么做?
如果有像array_count_values这样的功能会不会很棒?
< /讽刺>
使用的一些示例代码:
$arr = array(...);
$valCounts = array_count_values($arr);
echo $valCounts['hey'];
我强烈推荐浏览php.net,并在-特别是学习array functions。
$count = 0;
foreach($array as $item) {
if($item == 'hey') {
$count++;
}
}
print $count;
该命令是array_count_values。检查
http://www.php.net/manual/en/function.array-count-values.php
你只需要循环在阵列上。
$x = 0;
foreach (array("hey","test","hey") as $value) {
if ($value === "hey") $x++;
}
对于效率较低,但更短,解决方案,你可以使用array_count_value
。
$counts = array_count_values(array("hey","test","hey"));
$x = $counts["hey"];
我注意到你正在使用一些[函数数组解引用](http://schlueters.de/blog/archives/138-Features-in-PHP-trunk-Array-dereferencing.html)。太糟糕的PHP不支持它(在任何发布的版本)。 – zzzzBov
抱歉,抱歉。最近没有写任何PHP代码。我会解决它。 –
谢谢你!这是工作:) – Daniel