배열로 변환하는 두 개의 JSON 개체가 있습니다. 공유 키 ( "locationCode")를 기반으로 두 배열을 결합하고 한 배열에서 다른 배열로 "주소"배열 데이터를 추가해야합니다.
CURL을 사용하여 원격 서버에서 JSON을 성공적으로 가져온 후 배열로 변환합니다.
$json1 = json_decode($jsonresult, true);
$json2 = json_decode($jsonresult2, true);
결과 배열은 다음과 같습니다.
$ json1 :
"maxResults":500,
"events":[
{
"eventCode":"20140001",
"eventId":"72",
"contact":{
"contactName":"John Doe",
"organization":"John Doe Inc.",
"notes":""
},
"location":{
"locationName":"Company Factory",
"locationCode":"factory",
"email":"",
"phone":"866-123-4567",
"tollfree":"",
"fax":"",
"url":"",
"notes":""
},
"timezone":"(GMT-08:00) Pacific Time (US & Canada)",
"primaryFormURL":"path/to/form"
},
{
"eventCode":"20140002",
"eventId":"73",
"contact":{
"contactName":"John Doe",
"organization":"John Doe Inc.",
"notes":""
},
"location":{
"locationName":"Company HQ",
"locationCode":"hq",
"email":"",
"phone":"866-123-4567",
"tollfree":"",
"fax":"",
"url":"",
"notes":""
},
"timezone":"(GMT-08:00) Pacific Time (US & Canada)",
"primaryFormURL":"path/to/form"
},
{
"eventCode":"20140003",
"eventId":"74",
"contact":{
"contactName":"John Doe",
"organization":"John Doe Inc.",
"notes":""
},
"location":{
"locationName":"Company HQ",
"locationCode":"factory",
"email":"",
"phone":"866-123-4567",
"tollfree":"",
"fax":"",
"url":"",
"notes":""
},
"timezone":"(GMT-08:00) Pacific Time (US & Canada)",
"primaryFormURL":"path/to/form"
}
]
$ json2 :
"maxResults":500,
"locations":[
{
"numberOfRooms":null,
"totalSpace":null,
"address":{
"line1":"1245 Anystreet, Building 600",
"line2":"",
"line3":"",
"line4":"",
"city":"Anycity",
"state":"CA",
"postalCode":"98765",
"country":"United States",
"intlState":""
},
"locationCode":"factory",
"desc":"",
"url":""
},
{
"numberOfRooms":null,
"totalSpace":null,
"address":{
"line1":"3421 Anystreet, Building 200",
"line2":"",
"line3":"",
"line4":"",
"city":"Anycity",
"state":"CA",
"postalCode":"97654",
"country":"United States",
"intlState":""
},
"locationCode":"hq",
"desc":"",
"url":""
}
]
이제 "locationCode"키 일치를 기반으로 두 배열을 결합해야합니다. 결합은 $ json2의 "주소"배열 데이터를 적절한 일치 배열 위치의 $ json1에 추가하는 것으로 구성됩니다. 다양한 다차원 배열 반복기를 시도해 왔지만 실제로 필요한 값을 한 배열에서 다른 배열로 선택적으로 이동하는 방법을 파악하는 데 어려움을 겪고 있습니다. 다음과 같이 일치하는 항목을 찾는 반복기가 있습니다.
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($json1));
$iterator2 = new RecursiveIteratorIterator(new RecursiveArrayIterator($json2));
foreach($iterator as $key1=>$value1) {
if($key1=="locationCode") {
foreach($iterator2 as $key2=>$value2) {
if($key2=="locationCode" && $value1==$value2){
echo $key1.' -- '.$value1.':::'.$key2.' -- '.$value2.'<br />';
}
}
}
}
일치하는 값을 성공적으로 출력합니다. 이제 "주소"배열 데이터를 가져 와서 일치가 식별 된 $ json1 내의 위치에 추가하려면 어떻게해야합니까?
먼저 json2를 locationCode 값을 키로, 주소 개체를 값으로 사용하여 새 배열로 처리합니다. 그런 다음 이벤트 배열을 살펴보고이 배열에서 위치 코드와 일치하는 항목을 찾을 수있는 경우 주소를 추가합니다.
$json1 = json_decode($jsonresult);
$json2 = json_decode($jsonresult2);
// map locations to associative array
$addresses = array();
foreach($json2['locations'] as $location) {
$addresses[$location->locationCode] = $location->address;
}
// add addresses to events
$events = $json1['events'];
array_walk($events, function (&$event, $key_not_used, $addresses) {
if(array_key_exists($event->locationCode, $addresses)) {
$event->address = $addresses[$event->locationCode];
}
});
OP 업데이트 : 다음은 최종 작동 코드입니다 ...
$json1 = json_decode($jsonresult);
$json2 = json_decode($jsonresult2);
// map locations to associative array
$addresses = array();
foreach($json2->locations as $currlocation) {
$addresses[$currlocation->locationCode] = $currlocation->address;
}
// add addresses to events
$events = $json1->events;
function add_address(&$event, $key_not_used, $searcharray) {
if(array_key_exists($event->location->locationCode, $searcharray)) {
$event->address = $searcharray[$event->location->locationCode];
}
}
array_walk($events, 'add_address', $addresses);
$merged_events = json_encode($events);
print_r($merged_events);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다