60

如何计算数组中值等于常数的元素数量?例子,

$myArray = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");

我怎么能直接知道里面有多少个“本”?

4

10 回答 10

135
$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];
于 2012-07-25T08:59:01.283 回答
37

您可以使用array_keyscount来做到这一点。

$array = array("blue", "red", "green", "blue", "blue");
echo count(array_keys($array, "blue"));

输出:

3
于 2012-07-25T09:10:39.373 回答
15

要计算二维数组中的值,这里是处理和获取特定值计数的有用片段-

    <?php
    
    $list = [
      ['id' => 1, 'userId' => 5],
      ['id' => 2, 'userId' => 5],
      ['id' => 3, 'userId' => 6],
    ];

    $userId = 5;
    
    echo array_count_values(array_column($list, 'userId'))[$userId]; // outputs: 2
    
于 2018-11-14T21:25:41.053 回答
9

使用array_count_values函数。

$countValues = array_count_values($myArray);

echo $countValues["Ben"];

于 2012-07-25T09:00:02.170 回答
6

使用array_count_values()功能。检查此链接http://php.net/manual/en/function.array-count-values.php

于 2012-07-25T08:58:10.177 回答
4
define( 'SEARCH_STRING', 'Ben' );

$myArray = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");

$count = count(array_filter($myArray,function($value){return SEARCH_STRING === $value;}));

echo $count, "\n";

输出:

3
于 2016-07-21T21:18:19.190 回答
2

尝试 array_count_values() 函数

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

输出:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

http://php.net/manual/en/function.array-count-values.php

于 2012-07-25T08:59:59.010 回答
1

试试 PHP 函数array_count_values

于 2012-07-25T09:00:57.940 回答
1

如果你想计算数组中所有相同的出现,这里有一个函数来计算它们,并将结果作为多维数组返回:

function countSame($array) {

$count = count($array);
$storeArray = array();
while ($count > 0) {
$count--;

if ($array[$count]) {
$a = $array[$count];
$counts = array_count_values($array);
$counts = $counts[$a];
$tempArray = array($a, $counts);
array_push($storeArray, $tempArray);

$keys = array_keys($array, $a);
foreach ($keys as $k) {
unset($array[$k]);
} //end of foreach ($keys as $k)
} //end of if ($array[$count])

} //end of while ($count > 0)

return $storeArray;

} //end of function countSame($array)
于 2016-03-11T02:05:49.067 回答
1

array_count_values仅适用于整数和字符串。如果您碰巧需要浮点/数值的计数(并且您不注意精度或表示的微小变化),则可以使用:

function arrayCountValues($arr) {
  $vals = [];
  foreach ($arr as $val) { array_push($vals,strval($val)); }
  $cnts = array_count_values($vals);
  arsort($cnts);
  return $cnts;
}

请注意,我$cnts将键作为字符串返回。重新转换它们很容易,但我正在尝试确定值的模式,所以我只需要重新转换第一个(几个)值。

我测试了一个循环的版本,创建一个计数数组而不是使用array_count_values,结果证明效率更高(可能提高 8-10%)!

于 2017-08-03T18:38:20.677 回答