0

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

3 Answers 3

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
            )

    )

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

Comments

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

1 Comment

This will certainly not do the required task.
0

At it's core, this is a simple matter of array transposition (swapping the first and second level keys). You have a couple of simple preparations that need to be implementing before transposing the data though. First you'll need to decode the json strings. Also, you'll need to settle on a technique to inject your new, preferred non-numeric keys (to become the second level keys).

I'll wrap this task in an immediately invoked functional expression so that the non-numeric keys can be describes as function arguments and dynamically fed to the transposing, nested-loop structure.

Code: (Demo)

$names = '{"3":"test","4":"exam"}';
$quantities = '{"3":"12","4":"19"}';

var_export(
    (function($name, $quantity) {
        $result = [];
        foreach (get_defined_vars() as $k => $row) {
            foreach ($row as $i => $v) {
                $result[$i][$k] = $v;
            }
        };
        return ['final' => $result];
    })(json_decode($names, true), json_decode($quantities, true))
);

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.