Php 如何使用group by对数组进行计数
我有一个数组Php 如何使用group by对数组进行计数,php,arrays,Php,Arrays,我有一个数组 Array ( [0] => stdClass Object ( [id] => 226 [city] => Dhaka ) [1] => stdClass Object ( [id] => 228 [city] => Charleston County ) [
Array
(
[0] => stdClass Object
(
[id] => 226
[city] => Dhaka
)
[1] => stdClass Object
(
[id] => 228
[city] => Charleston County
)
[2] => stdClass Object
(
[id] => 229
[city] => Dhaka
)
[3] => stdClass Object
(
[id] => 232
[city] => Dhaka
)
[4] => stdClass Object
(
[id] => 234
[city] => Miami-Dade County
)
来达卡三次
所以我希望我的结果是达卡=3,迈阿密戴德郡=1,查尔斯顿郡=1
这是一个示例数组,所有数据都将动态出现PHP>=5.3.0:
$result = array_count_values(array_map(function($v) {
return $v->city;
}, $array));
对于早期版本,为什么?您需要构建一个数组映射函数,或者在数组中循环,并构建一个一维函数进行计数。您可以在数组上循环,并在运行时对每个城市的实例进行计数
$city_counts = array(); // create an array to hold the counts
foreach ($array as $city_object) { // loop over the array of city objects
// checking isset will prevent undefined index notices
if (isset($city_counts[$city_object->city])) {
$city_counts[$city_object->city]++; // increment the count for the city
} else {
$city_counts[$city_object->city] = 1; // initialize the count for the city
}
}
请告诉我们你试过了,告诉我们你的php代码。这听起来非常类似于这篇文章没有问题。真可惜,不会的。这是一个非常方便的功能。