1

I have two jsons which have both some same keys and i want to merge them based on the key that have.

my first json: {"3":"test","4":"exam"}

My second json: {"3":"12","4":"19"}

i want to have an array like this:

array("final") {
[3]=> {
  "name" => "test"
  "quantity" => "12"
 } 
 [4]=> {
  "name" => "exam"
  "quantity" => "19"
 } 
}

INFJ
  • 39
  • 5
  • 1
    Possible duplicate of [Merging two json in PHP](https://stackoverflow.com/questions/20286208/merging-two-json-in-php) – Yaser Darzi Oct 24 '19 at 06:33

2 Answers2

1

Decode the json objects to array

 $x = json_decode($x);
 $y = json_Decode($y);
 $res['final'] = [];
 foreach($x as $key => $value)
 {
  foreach($y as $k => $v)
  {
    if($key == $k)
    {
        $res['final'][$key]['name'] = $value;
        $res['final'][$key]['quantity'] = $v;
    }
  }
 }
 print_r($res);

Output will be

Array
(
[final] => Array
    (
        [3] => Array
            (
                [name] => test
                [quantity] => 12
            )

        [4] => Array
            (
                [name] => exam
                [quantity] => 19
            )

    )

)
Jithesh Jose
  • 1,781
  • 1
  • 6
  • 17
0

You can use json_decode and array_merge

First json_decode your first and second json

$firstJson = json_decode(jsonData); 
$secondJson = json_decode(jsonData);

And merge them using array_merge

array_merge($first_json, $secondJson);
Poldo
  • 1,924
  • 1
  • 11
  • 27