【问题标题】:How to merge two jsons and save them as array如何合并两个json并将它们保存为数组
【发布时间】:2020-02-20 10:21:36
【问题描述】:

我有两个 json,它们都有一些相同的键,我想根据键合并它们。

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

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

我想要一个这样的数组:

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

【问题讨论】:

标签: arrays json laravel


【解决方案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
            )

    )

)

【讨论】:

    【解决方案2】:

    您可以使用 json_decodearray_merge

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

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

    并使用 array_merge 合并它们

    array_merge($first_json, $secondJson);
    

    【讨论】:

      猜你喜欢
      • 2017-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-30
      相关资源
      最近更新 更多