array_merge~配列同士の結合(マージ)

array_merge()

array_merge()の構文は「array_merge(配列1 [, はいれつ2・・・]);」です。
array_merge()は複数の配列を結合します。前の配列の後部に次の配列を追加し、これを繰り返すことができます。この関数は一次元にのみ対応しています。キーがプラスであれば0から始まる数値に置換されます。この場合、キーに対する値は残り、割り当てられるキーの番号が変わります。キーが文字で、かつ同じキーを持つ配列同士を結合する場合は、後から追加されるキーの値によって前の配列の値が上書きされます。

配列をプラスでつないで結合すると前の配列のキーの値が保持されます。このため、前の配列と追加した配列に同じキーがある場合には、前の配列のキーと値が残る形になって追加された方のキーと値のセットは消えます。

1
2
3
$str1 = ["1" => "a","2" => "b","3" => "c"];
$str2 = ["1" => "f","4" => "d","5" => "e"];
print_r(array_merge($str1, $str2));
実行結果:
(
[0] => a
[1] => b
[2] => c
[3] => f
[4] => d
[5] => e
)
1
2
3
4
$a = ["a" => "1","b" => "2","c" => "3"];
$b = ["d" => "4","e" => "5","f" => "6"];
$c = ["a" => "9","g" => "7","h" => "8"];
print_r(array_merge($a, $b, $c));
実行結果:
(
[a] => 9
[b] => 2
[c] => 3
[d] => 4
[e] => 5
[f] => 6
[g] => 7
[h] => 8
)
1
2
3
4
5
// 一次元配列をプラスで結合
$str1 = ["1" => "a","2" => "b","3" => "c"];
$str2 = ["1" => "f","5" => "d","6" => "e"];
$str=$str1+$str2;
print_r($str);
実行結果:
(
[1] => a
[2] => b
[3] => c
[5] => d
[6] => e
)
1
2
3
4
5
6
// 一次元配列をプラスで結合
$a = ["a" => "1","b" => "2","c" => "3"];
$b = ["d" => "4","e" => "5","f" => "6"];
$c = ["a" => "9","g" => "7","h" => "8"];
$d=$a+$b+$c;
print_r($d);
実行結果:
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
[e] => 5
[f] => 6
[g] => 7
[h] => 8
)

array_merge_recursive()

array_merge_recursive()の構文は「array_merge_recursive(配列1 [, はいれつ2・・・]);」です。
array_merge_recursive()は二つ以上のはいれつを多次元配列で再帰的に結合します。

1
2
3
4
5
6
7
8
$a = ["a" => ["b" => "1","c" => "2","d" => "3"]];
$b = ["e" => ["a" => "4","f" => "5","g" => "6"]];
$c = ["a" => ["b" => "7","i" => "8","j" => "9"]];
echo '
<pre>';
print_r(array_merge_recursive($a, $b, $c));
echo '</pre>
';
実行結果:

(
    [a] => Array
        (
            [b] => Array
                (
                    [0] => 1
                    [1] => 7
                )

            [c] => 2
            [d] => 3
            [i] => 8
            [j] => 9
        )

    [e] => Array
        (
            [a] => 4
            [f] => 5
            [g] => 6
        )

)