2014-12-10 4 views
3

JSON에 이미 들어있는 성분이 들어있는 웹 사이트의 쇼핑 목록 앱을 작성하려고합니다.PHP에서 JSON 피드 2 개를 병합하고 값을 더하기

전체 코드는 하단에 있지만 설명 만하고 있습니다. 내가하고자하는 것은 '이름'(그리고 바람직하게는 '척도')이 일치 할 때 '수량'의 값을 추가하여 2 개의 배열을 병합 할 수있게하는 것입니다.

'해바라기 기름'은 JSON 피드에 모두 나와 있습니다. 나는 같은 출력을 원하는 :

{"name":"Sunflower oil","quantity":110,"measure":"ml"} 

하지만 현재 JSON을 덮어 출력은 다음과 같습니다

{"name":"Sunflower oil","quantity":10,"measure":"ml"}, 

내가 잘못 뭘하는지의 모든 지원은 크게 JSON 및 객체로 평가 될 것입니다/배열은 내 장점이 아닙니다!

<?php 
$a = '{"ingredients":[{"name": "Sunflower oil","quantity": 100,"measure": "ml"}]}'; 
$b = '{"ingredients":[{"name": "Sunflower oil","quantity": 10,"measure": "ml"},{"name": "Fennel seeds","quantity": 1,"measure": "teaspoon"},{"name": "Garlic","quantity": 1,"measure": "clove"}]}'; 
print_r(json_encode(array_merge(json_decode($a, true),json_decode($b, true)))); 
?> 

답변

1

당신은 예상 결과를 얻으려면 다음 코드를 사용할 수 있습니다 :

<?php 
$a = '{"ingredients":[{"name": "Sunflower oil","quantity": 100,"measure": "ml"},{"name": "Olive oil","quantity": 50,"measure": "ml"}]}'; 
$b = '{"ingredients":[{"name": "Sunflower oil","quantity": 10,"measure": "ml"},{"name": "Fennel seeds","quantity": 1,"measure": "teaspoon"},{"name": "Garlic","quantity": 1,"measure": "clove"}]}'; 

$aArr = json_decode($a, true); 
$bArr = json_decode($b, true); 
$sumArr = array("ingredients" => array()); 

foreach ($aArr['ingredients'] as $valA) { 
    foreach ($bArr['ingredients'] as $keyB => $valB) { 
     if ($valA['name'] == $valB['name'] && 
      $valA['measure'] == $valB['measure']) { 

      $valA['quantity'] += $valB['quantity']; 
      $sumArr['ingredients'][] = $valA; 

      unset($bArr['ingredients'][$keyB]); 
      continue 2; 
     } 
    } 
    $sumArr['ingredients'][] = $valA; 
} 
$sumArr['ingredients'] = array_merge($sumArr['ingredients'], $bArr['ingredients']); 
print_r(json_encode($sumArr)); 
?> 
+0

감사합니다 :)이 위대한입니다 - 사전에

덕분에 여기 내 코드입니다. – Nick

관련 문제