如何合并两个json并将其保存为数组

时间:2019-10-24 06:19:28

标签: arrays json laravel

我有两个具有相同密钥的json,我想根据具有的密钥合并它们。

我的第一个json:{"3":"test","4":"exam"}

我的第二个json:{"3":"12","4":"19"}

我想要一个像这样的数组:

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

2 个答案:

答案 0 :(得分:1)

将json对象解码为数组

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

输出将为

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

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

    )

)

答案 1 :(得分:0)

您可以使用 json_decode array_merge

第一个json_decode您的第一个和第二个json

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

并使用array_merge合并它们

array_merge($first_json, $secondJson);