在array_merge和array1 + array2之间妥协

时间:2013-06-04 06:28:25

标签: php arrays merge

我想结合两个数组,覆盖重复的键,但不想重新索引所有索引。是否有某些功能可以做到这一点?

我需要两者的联合结构,因此每个密钥中的哪个内容无关紧要。

数组1:

[820]
   [name1]
      [id] = "My Name"
   [name2]
      [id] = "Your Name"
[830]
   [id] = "Mothers Name"

数组2:

[815]
   [name1]
      [id] = "IDs Name"
[820]
   [name1]
      [id] = "Names Name"
   [id] = "Last ID ID"

结果应为

[815]
   [name1]
      [id] = //does not matter
[820]
   [name1]
      [id] = //does not matter
   [name2]
      [id] = //does not matter
   [id] = //does not matter
[830]
   [id] = //does not matter

1 个答案:

答案 0 :(得分:0)

$result = array();
foreach ($array1 as $key => $value){
    if(isset($array2[$key]))
        $result[$key] = array_merge($value, $array2[$key]);
    else 
        $result[$key] = $value;
}
foreach ($array2 as $key => $value){
    if(isset($array1[$key]))
        $result[$key] = array_merge($value, $array1[$key]);
    else 
        $result[$key] = $value;
}