我需要计算解码json后有多少数组相等。
{ "IP": [ { "C_P": "US", "C_L": "United States" }, { "C_P": "IT", "C_L": "ITALY" }, { "C_P": "US", "C_L": "United States" }, { "C_P": "CO", "C_L": "Colombia" }, { "C_P": "US", "C_L": "United States" } ] }
使用对数组“C_P”进行计数的进程循环,结果应为:
3: US
1: IT
1: CO
感谢。
答案 0 :(得分:1)
$result = json_decode($json);
$countArray = array();
foreach ($result as $key => $element) {
foreach ($element as $cp)
if (isset($countArray[$cp->C_P]))
$countArray[$cp->C_P] ++;
else
$countArray[$cp->C_P] = 1;
}
答案 1 :(得分:0)
尝试以下内容
$array = (array)json_decode($a, true);
$index = array();
foreach ($array['IP'] as $key => $value){
unset($value['C_L']);
foreach ($value as $key2 => $value2){
if (array_key_exists($value2, $index)){
$index[$value2]++;
} else {
$index[$value2] = 1;
}
}
}
print_r($index);
<强>输出:强>
Array
(
[US] => 3
[IT] => 1
[CO] => 1
)