如何计算数组中值等于常数的元素数量?例子,
$myArray = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
我怎么能直接知道里面有多少个“本”?
$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];
您可以使用array_keys和count来做到这一点。
$array = array("blue", "red", "green", "blue", "blue");
echo count(array_keys($array, "blue"));
输出:
3
要计算二维数组中的值,这里是处理和获取特定值计数的有用片段-
<?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
使用array_count_values()
功能。检查此链接http://php.net/manual/en/function.array-count-values.php
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
尝试 array_count_values() 函数
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
输出:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
试试 PHP 函数array_count_values
。
如果你想计算数组中所有相同的出现,这里有一个函数来计算它们,并将结果作为多维数组返回:
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)
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%)!