在PHP中合并2个数组

时间:2016-02-25 12:38:23

标签: php arrays

我有2个数组,其中包含以下示例结构:

$json1 = '[[
{
  "Str1":"ABC",
  "Str2": "Some Value",
  "Str3": "Something"
},
{
  "Str1": "DEF",
  "Str2": "Another Value",
  "Str3": "Test"
},
{
  "Str1": "GHI",
  "Str2": "NULL",
  "Str3": "Blah"
}]]';

$json2 = '[{
  "ID": "1",
  "ABC": "Hello",
  "DEF": "Test",
  "GHI": "Something"
}]';


$arr1 = json_decode($json1);
$arr2 = json_decode($json2);

我希望他们加入PHP"按键"。密钥为IDABCDEF,(仅为示例名称)等。

键是阵列1 中阵列的名称。此外,数组2 中每个数组的第一个条目是。不幸的是,它们的顺序不同。

所以我需要迭代两个数组并检查键是否相同,如果是,则将数组2 的值复制到数组1 。像这样:

if($array1[$key] == $array2[$key]){
    $array1[$key] += $array2[$key];
}

所需的结果只是一些数组通过"键":

合并在一起
[0] => array(4){
"ABC" => "Hello",
"Str 1" => "ABC",
"Str 2" => "Some Value",
"Str 3" => "Something"
}
[1] => array(4){
"DEF" => "Test",
"Str 1" => "DEF",
"Str 2" => "Another Value",
"Str 3" => "Test"
}
[2] ...

2 个答案:

答案 0 :(得分:0)

试试这个:

$json1 = '[[
{
  "Str1":"ABC",
  "Str2": "Some Value",
  "Str3": "Something"
},
{
  "Str1": "DEF",
  "Str2": "Another Value",
  "Str3": "Test"
},
{
  "Str1": "GHI",
  "Str2": "NULL",
  "Str3": "Blah"
}]]';

$json2 = '[{
  "ID": "1",
  "ABC": "Hello",
  "DEF": "Test",
  "GHI": "Something"
}]';


$arr1 = json_decode($json1, true);
$arr2 = json_decode($json2, true);

$arr_merged = array_fill_keys( array_keys($arr2[0], null );
foreach($json2[0] as $k => $v) {
        $arr_merged[$k] => array($v);
}
foreach($json1 as $src) {
    $key = $json1['Str1'];
    if(!array_key_exists($key, $arr_merged)) {
        $arr_merged[$key] = array();
    }
    foreach($src as $k => $v) {
        $arr_merged[$key][$k] = $v;
    }
}

答案 1 :(得分:0)

这是我的解决方案:

[  
   [  
      {  
         "Str1":"ABC",
         "Str2":"Some Value",
         "Str3":"Something",
         "ABC":"Hello"
      },
      {  
         "Str1":"DEF",
         "Str2":"Another Value",
         "Str3":"Test",
         "DEF":"Test"
      },
      {  
         "Str1":"GHI",
         "Str2":"NULL",
         "Str3":"Blah",
         "GHI":"Something"
      }
   ]
]

这会产生以下输出:

X