Concatenating and adding values ​​of 2 JSON channels in PHP

I'm trying to write a shopping list app for a site that already has components listed in JSON.

The complete code is below, but just for explanation; What I'm going to do is concatenate the 2 arrays by adding values ​​from "count" when "name" matches (and preferably also "measure").

eg. "Sunflower oil" is listed in both JSON feeds. I want it to output like:

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

      

but it is currently overwriting the JSON and the output is:

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

      

Any help on what I am doing wrong would be greatly appreciated as JSON and objects / arrays are not my forte!

Thanks in advance - here's my code:

<?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))) );
?>

      

+3


source to share


1 answer


You can use the following code to get the expected result:



<?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 ));
?>

      

+1


source







All Articles