phparraysjsontransposemerging-data

Merge and transpose the data from two json strings containing flat array structures


I have two JSONs which both have the same keys and I want to merge them based on their related keys.

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"
  } 
}  

Solution

  • 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
                )
    
        )
    
    )