我有许多JSON,例如:
第1项:
{
"countries_views": [
{
"thecount": "563",
"country": "Greece"
},
{
"thecount": "48",
"country": "United States"
},
{
"thecount": "11",
"country": "Luxembourg"
},
{
"thecount": "7",
"country": "Germany"
},
{
"thecount": "6",
"country": "Cyprus"
},
{
"thecount": "2",
"country": "India"
},
{
"thecount": "2",
"country": "France"
},
{
"thecount": "2",
"country": "United Kingdom"
},
{
"thecount": "1",
"country": "Nigeria"
},
{
"thecount": "1",
"country": "Russia"
}
]
}
第2项:
{
"countries_views": [
{
"thecount": "1037",
"country": "Greece"
},
{
"thecount": "17",
"country": "United States"
},
{
"thecount": "17",
"country": "Cyprus"
},
{
"thecount": "12",
"country": "Germany"
},
{
"thecount": "11",
"country": ""
},
{
"thecount": "4",
"country": "United Kingdom"
},
{
"thecount": "4",
"country": "Australia"
},
{
"thecount": "2",
"country": "Belgium"
},
{
"thecount": "1",
"country": "Russia"
},
{
"thecount": "1",
"country": "Argentina"
}
]
}
等等!我需要做的是将1个数组中的数据与PHP 合并/合并,我需要添加重复项的值。最终结果应如下所示:
{
"countries_views": [
{
"thecount": "**1600**",
"country": "Greece"
},
{
"thecount": "**65**",
"country": "United States"
},
etcetcetc
]
}
答案 0 :(得分:0)
首先解析JSON数据,然后我们遍历数组以找到重复项并添加它们。
<?php
// emit the code of parsing json. (see function json_decode)
$arr1 = [
(object)['thecount' => 563, 'country' => 'Greece'],
(object)['thecount' => 12, 'country' => 'US'],
(object)['thecount' => 15, 'country' => 'UK'],
];
$arr2 = [
(object)['thecount' => 1563, 'country' => 'Greece'],
(object)['thecount' => 152, 'country' => 'CN'],
];
foreach ($arr1 as $each) {
$exists = false;
foreach ($arr2 as &$e) {
if ($e->country == $each->country) {
$e->thecount += $each->thecount;
$exists = true;
}
}
if (!$exists) {
array_push($arr2, $each);
}
}
$res = $arr2;
var_dump($res);
以下是如何在你的例子中获得$ arr1,$ arr2。
<?php
$arr1_obj = json_decode($item1);
$arr2_obj = json_decode($item2);
$arr1 = $arr1_obj->countries_views;
$arr2 = $arr2_obj->countries_views;