tl;dr
array_replace()
、array_replace_recursive()
を使う。
$array1 = [
'hoge' => 'fuga',
'piyo',
'fizz',
'arr' => [
'key' => 'val'
],
'aaa' => 'bbb',
'arr2' => [
'key1' => 'val1',
'key2' => 'val2',
'str1'
],
20 => 30,
];
$array2 = [
'hoge' => 'hogehoge',
'piyopiyo',
'foo' => 'bar',
'buzz',
'arr' => 'str',
'arr2' => [
'key2' => 'value2',
'key3' => 'value3',
'str2'
],
21 => 40,
];
print_r(array_replace($array1, $array2));
print_r(array_replace_recursive($array1, $array2));
array_replace
Array
(
[hoge] => hogehoge
[0] => piyopiyo
[1] => buzz
[arr] => str
[aaa] => bbb
[arr2] => Array
(
[key2] => value2
[key3] => value3
[0] => str2
)
[20] => 30
[foo] => bar
[21] => 40
)
array_replace_recursive
Array
(
[hoge] => hogehoge
[0] => piyopiyo
[1] => buzz
[arr] => str
[aaa] => bbb
[arr2] => Array
(
[key1] => val1
[key2] => value2
[0] => str2
[key3] => value3
)
[20] => 30
[foo] => bar
[21] => 40
)
他のマージ関数の場合
すでに他所で書かれておりますが、以下にまとめてみました。
※同じ配列で実行した結果です。
array_merge
print_r(array_merge($array1, $array2));
result
Array
(
[hoge] => hogehoge
[0] => piyo
[1] => fizz
[arr] => str
[aaa] => bbb
[arr2] => Array
(
[key2] => value2
[key3] => value3
[0] => str2
)
[2] => 30
[3] => piyopiyo
[foo] => bar
[4] => buzz
[5] => 40
)
array_merge_recursive
print_r(array_merge_recursive($array1, $array2));
result
Array
(
[hoge] => Array
(
[0] => fuga
[1] => hogehoge
)
[0] => piyo
[1] => fizz
[arr] => Array
(
[key] => val
[0] => str
)
[aaa] => bbb
[arr2] => Array
(
[key1] => val1
[key2] => Array
(
[0] => val2
[1] => value2
)
[0] => str1
[key3] => value3
[1] => str2
)
[2] => 30
[3] => piyopiyo
[foo] => bar
[4] => buzz
[5] => 40
)
array1 + array2
print_r($array1 + $array2);
result
Array
(
[hoge] => fuga
[0] => piyo
[1] => fizz
[arr] => Array
(
[key] => val
)
[aaa] => bbb
[arr2] => Array
(
[key1] => val1
[key2] => val2
[0] => str1
)
[20] => 30
[foo] => bar
[21] => 40
)
array2 + array1
print_r($array2 + $array1);
result
Array
(
[hoge] => hogehoge
[0] => piyopiyo
[foo] => bar
[1] => buzz
[arr] => str
[arr2] => Array
(
[key2] => value2
[key3] => value3
[0] => str2
)
[21] => 40
[aaa] => bbb
[20] => 30
)
ついで
array_replace
、array_replace_recursive
の使用できるバージョンは PHP 5 >= 5.3.0 となります。
そんな方いらっしゃらないかと思いますが、もし、5.3未満で使いたい場合は、以下に代替関数を載せておきます。
なお、テスト通してないので、ご使用には十分ご注意下さい。
if (!function_exists('array_replace')) {
function array_replace(array $a1, array $a2) {
foreach ($a2 as $k => $v) {
$a1[$k] = $v;
}
return $a1;
}
}
if (!function_exists('array_replace_recursive')) {
function array_replace_recursive(array $a1, array $a2) {
foreach ($a2 as $k => $v) {
if (is_array($v) && isset($a1[$k]) && is_array($a1[$k])) {
$v = array_replace_recursive($a1[$k], $v);
}
$a1[$k] = $v;
}
return $a1;
}
}