使用PHP计算数组中特定值的出现次数

36
我正在尝试寻找一个原生的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

我知道如何创建自己的函数,但为什么要重复造轮子呢?

6个回答

57
function array_count_values_of($value, $array) {
    $counts = array_count_values($array);
    return $counts[$value];
}

虽然不是母语,但这很简单。;-)

或者:

echo count(array_filter($array, function ($n) { return $n == 6; }));

或者:

echo array_reduce($array, function ($v, $n) { return $v + ($n == 6); }, 0);

或者:

echo count(array_keys($array, 6));

个人而言,我会选择使用array_reduce版本,因为我喜欢折叠函数。 :o) - deceze
count(array_keys($array, 6, $strict = false)) 中可以提供 $strict 参数,如果提供为 true 将使用严格比较 (=== 运算符而不是 ==)。 - Pedro Sanção

14

这个解决方案可能接近您的要求

$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 )

有关详细信息,请参阅。


14

自 PHP 5.4.0 起,您可以对由 array_count_values() 返回的数组使用函数数组解引用来访问索引[6]

$instances = array_count_values($array)[6];

如果要检查并在找不到时分配 0

$instances = array_count_values($array)[6] ?? 0;

如果存在0值,这将引发一个错误,它是6的一部分。 - Andrei
@Andrei 添加了一个选项。 - AbraCadaver

4
假设我们有以下数组:
     $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*/

1
如果可能的话,请解释一下你的代码是如何工作的,或者它是如何解决问题的。 - Compass
@Compass 我解释了这个函数并添加了一个例子。希望有所帮助! - Kareem

1

假设我有这样一个数组:

$array = array('', '', 'other', '', 'other');

$counter = 0;
foreach($array as $value)
{
  if($value === '')
    $counter++;
}
echo $counter;

这将给出数组中“ ”重复的次数。

0

这正是你正在寻找的。

<?php
 $MainString = 'Yellow Green Orange Blue Yellow Black White Purple';
 $FinderString = 'Yellow Blue White';
 $mainArray = explode(" ", $MainString);
 $findingArray = explode(" ", $FinderString);
 $count = 0;
 $eachtotal = array_count_values($mainArray);
 foreach($findingArray as $find){

    $count += $eachtotal[$find];
 }
 echo $count;


?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接