查找多维数组中具有特定值项的简单方法
<?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]; // 输出:2
?>
(PHP 4, PHP 5, PHP 7, PHP 8)
array_count_values — 统计数组中每个不同值的出现次数
array
要统计值的数组
返回一个关联数组,键是 array
中的值,值是它们的计数。
示例 #1 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
$list = [
['id' => 1, 'userId' => 5],
['id' => 2, 'userId' => 5],
['id' => 3, 'userId' => 6],
];
$userId = 5;
echo array_count_values(array_column($list, 'userId'))[$userId]; // 输出:2
?>
我找不到进行不区分大小写匹配的值计数函数,所以我自己写了一个快速简便的解决方案
<pre><?php
function array_icount_values($array) {
$ret_array = array();
foreach($array as $value) {
foreach($ret_array as $key2 => $value2) {
if(strtolower($key2) == strtolower($value)) {
$ret_array[$key2]++;
continue 2;
}
}
$ret_array[$value] = 1;
}
return $ret_array;
}
$ar = array('J. Karjalainen', 'J. Karjalainen', 60, '60', 'J. Karjalainen', 'j. karjalainen', 'Fastway', 'FASTWAY', 'Fastway', 'fastway', 'YUP');
$ar2 = array_count_values($ar); // 普通匹配
$ar = array_icount_values($ar); // 不区分大小写匹配
print_r($ar2);
print_r($ar);
?></pre>
这将打印
数组
(
[J. Karjalainen] => 3
[60] => 2
[j. karjalainen] => 1
[Fastway] => 2
[FASTWAY] => 1
[fastway] => 1
[YUP] => 1
)
数组
(
[J. Karjalainen] => 4
[60] => 2
[Fastway] => 4
[YUP] => 1
)
我不知道它的效率如何,但它似乎可以工作。我的一个脚本需要这个函数,所以我想分享一下。
这是一个处理一个或多个具有相似值的数组的版本
使用 $lower=true/false 来忽略/设置大小写敏感。
<?php
$ar1[] = array("red","green","yellow","blue");
$ar1[] = array("green","yellow","brown","red","white","yellow");
$ar1[] = array("red","green","brown","blue","black","yellow");
#$ar1= array("red","green","brown","blue","black","red","green"); // 可使用一个或多个数组
$res = array_icount_values ($ar1);
print_r($res);
function array_icount_values($arr,$lower=true) {
$arr2=array();
if(!is_array($arr['0'])){$arr=array($arr);}
foreach($arr as $k=> $v){
foreach($v as $v2){
if($lower==true) {$v2=strtolower($v2);}
if(!isset($arr2[$v2])){
$arr2[$v2]=1;
}else{
$arr2[$v2]++;
}
}
}
return $arr2;
}
/*
输出结果:
Array
(
[red] => 3
[green] => 3
[yellow] => 4
[blue] => 2
[brown] => 2
[white] => 1
[black] => 1
)
*/
?>