统计数组中不同元素的个数
$fruits = array(“apple”, “orange”, “banana”, “pear”, “apple”, “apple”);
$count_fruits = array_count_values($fruits);
print_r($count_fruits);
Array (
[apple] => 3
[orange] => 1
[banana] => 1
[pear] => 1
)
统计数组中某一元素出现的次数
方法一:
$fruits = array(“apple”, “orange”, “banana”, “pear”, “apple”, “apple”);
$count_apple = 0;
foreach ($fruits as $fruit) {
if ($fruit == “apple”) {
$count_apple++;
}
}
echo $count_apple; //输出3
方法二:
$fruits = array(“apple”, “orange”, “banana”, “pear”, “apple”, “apple”);
$count_apple = count(array_filter($fruits, function($fruit) {
return $fruit == “apple”;
}));
echo $count_apple; //输出3
统计二维数组某个值出现的次数
[‘id’ => 1, ‘age’ => 25],
[‘id’ => 2, ‘age’ => 25],
[‘id’ => 3, ‘age’ => 36],
];
//把值提取出来转成一维数组
$arr=array_column($list,’age’);
//数组的值作为键名,该值在数组中出现的次数作为值
$arr=array_count_values($arr);