计数特定值Occurence在一个阵列,PHP [英] Counting Occurence of Specific Value in An Array With PHP
问题描述
乡亲。我试图找到一个本地的PHP函数,让我来数出数组中某个特定值出现的次数。我熟悉array_count_values()函数,而是返回所有值的计数在数组中。是否有一个功能,可以传递价值,只返回实例计数为特定值?例如:
$阵列=阵列(1,2,3,3,3,4,4,5,6,6,6,6,7);$实例= some_native_function(6,$数组); // $实例将等于4
我知道如何crearte我自己的功能,但为什么要重新发明轮子?在此先感谢!
函数array_count_values_of(价值$,$阵列){
$数= array_count_values($数组);
返回$计数[$值];
}
不是的原始的,不过来了,这是很简单的。 ; - )
或者
回声计数(array_filter($阵列功能($ N){返回$ N == 6;}));
或者
回声array_reduce($阵列功能($ V,$ N){返回$ V +($ N == 6);},0);
或者
回声计数(array_keys($阵列,6));
folks. I am trying to find a native PHP function that will allow me to count the number of occurences of a particular value in an array. I am familiar with the array_count_values() function, but that returns the count of all values in an array. Is there a function that allows you to pass the value and just return the instance count for that particular value? For example:
$array = array(1, 2, 3, 3, 3, 4, 4, 5, 6, 6, 6, 6, 7);
$instances = some_native_function(6, $array); //$instances will be equal to 4
I know how to crearte my own function, but why re-invent the wheel? Thanks in advance!
function array_count_values_of($value, $array) {
$counts = array_count_values($array);
return $counts[$value];
}
Not native, but come on, it's simple enough. ;-)
Alternatively:
echo count(array_filter($array, function ($n) { return $n == 6; }));
Or:
echo array_reduce($array, function ($v, $n) { return $v + ($n == 6); }, 0);
Or:
echo count(array_keys($array, 6));
这篇关于计数特定值Occurence在一个阵列,PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!