Merge nested json values in php
Get the solution ↓↓↓In PHP, I am struggling to merge two json objects ($old
and$new
) with nested values:
echo "OLD: ".$old;
echo "NEW: ".$new;
Result:
{-code-4}
Expected result I needed:
{"4":{"deu":1, "eng":2, "fra":1}}
Attempts:
Triedjson_decode()
andarray_merge()
but got a json result with missing key4
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 key4
is missing from the result
Answer
Solution:
You need to useforeach()
as well along withjson_decode()
andarray_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
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: php_network_getaddresses: getaddrinfo failed: temporary failure in name resolution
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.