다음과 같은 많은 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"
}
]
}
등등! 내가해야 할 일은이 데이터를 PHP로 1 배열에 결합 / 병합 하는 것이며 Duplicates 값 을 추가 해야합니다 . 최종 결과는 다음과 같아야합니다.
{
"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;
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다