1

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

3
  • 1
    Not sure why you would expect that result from just concatenating the values? Have you actually made any real attempt to implement your requirement? Commented Apr 6, 2021 at 7:13
  • yes i tried multiple potental attempts with json_decode and array_merge but for i get a json result with missing key "4", in other words I get this {{"deu":1, "eng":2, "fra":1}} or this [{"deu":1, "eng":1, "fra":1},{"deu":1, "eng":2}] as you can see the key "4" is missing from the result Commented Apr 6, 2021 at 7:15
  • 1
    Show your best effort so far then, instead of the pointless code you provided above. Maybe you're actually not too far from the solution. Commented Apr 6, 2021 at 7:17

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.