У меня есть ряд 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
]
}
Сначала анализируем данные 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;
Других решений пока нет …