我正在尝试寻找一个原生PHP函数,它允许我计算数组中特定值出现的次数。我熟悉array_count_values()函数,但它返回数组中所有值的计数。是否有一个函数允许您传递该值并只返回该特定值的实例计数?例如:
$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
我知道如何创建自己的函数,但为什么要重新发明轮子呢?
发布于 2011-05-10 12:43:48
此解决方案可能接近您的要求
$array = array(1, 2, 3, 3, 3, 4, 4, 5, 6, 6, 6, 6, 7);
print_r(array_count_values($array));
Result:
Array
( [1] => 1 ,[2] => 1 , [3] => 3, [4] => 2,[5] =>1, [6] => 4, [7] => 1 )
为了details。
发布于 2015-07-02 02:39:00
从PHP5.4.0开始,您可以对由array_count_values()
生成的数组的索引[6]
使用函数数组取消引用
$instances = array_count_values($array)[6];
因此,如果找不到,则检查并分配0
:
$instances = array_count_values($array)[6] ?? 0;
发布于 2014-10-24 10:55:11
假设我们有以下数组:
$stockonhand = array( "large green", "small blue", "xlarge brown", "large green", "medieum yellow", "xlarge brown", "large green");
1)将此函数复制并粘贴到页面顶部。
function arraycount($array, $value){
$counter = 0;
foreach($array as $thisvalue) /*go through every value in the array*/
{
if($thisvalue === $value){ /*if this one value of the array is equal to the value we are checking*/
$counter++; /*increase the count by 1*/
}
}
return $counter;
}
2)接下来需要做的就是在每次要计算任何数组中的任何特定值时都应用该函数。例如:
echo arraycount($stockonhand, "large green"); /*will return 3*/
echo arraycount($stockonhand, "xlarge brown"); /*will return 2*/
https://stackoverflow.com/questions/5945199
复制相似问题