我有一个国家/地区列表:
Ghana
Kenya
Thailand
India
Cameroon
Tanzania
Kenya
Cameroon
India
Uganda
Argentina
Kenya
Uganda
我使用 foreach()
来显示国家/地区:
$json = file_get_contents('PATH_TO_JSON');
$obj = json_decode($json, true);
foreach($obj as $project_info){
$list = $project_info['country'];
}
我的问题是如何显示所有相同国家/地区的计数?
示例:
Kenya(3)
India(2)
... and so on
我尝试了 array_count_values()
但无法让它工作。
最佳答案
您需要从每个子数组中提取country
值,然后对它们进行计数:
$array = json_decode($json, true);
$countries_count = array_count_values(array_column($array, 'country'));
foreach($countries_count as $country => $count) {
echo "$country ($count)";
}
我使用 $array
而不是 $obj
因为它是一个数组而不是一个对象。
关于php - 如何计算多维数组中所有相同的项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36317459/