Reputation: 69
In PHP, I am struggling to merge two json objects ( $old
and $new
) with nested values:
echo "OLD: ".$old;
echo "NEW: ".$new;
Result:
OLD: {"4":{"deu":1, "eng":1, "fra":1}}
NEW: {"4":{"deu":1, "eng":2}}
Expected result I needed:
{"4":{"deu":1, "eng":2, "fra":1}}
Attempts:
Tried json_decode()
and array_merge()
but got a json result with missing key 4
I got these kind of results:
{{"deu":1, "eng":2, "fra":1}}
//or
[{"deu":1, "eng":1, "fra":1},{"deu":1, "eng":2}]
As you can see the key 4
is missing from the result
Upvotes: 1
Views: 139
Reputation: 72299
You need to use foreach()
as well along with json_decode()
and array_merge()
<?php
$old = '{"4":{"deu":1, "eng":1, "fra":1}}';
$new = '{"4":{"deu":1, "eng":2}}';
$oldArray = json_decode($old,true);
$newArray = json_decode($new,true);
$finalArray =[];
foreach($oldArray as $key=>$value){
$finalArray[$key] = array_merge($value,$newArray[$key]);
}
print_r($finalArray);
echo json_encode($finalArray);
Output: https://3v4l.org/i0QLt
Upvotes: 2