どうも、ちょげ(@chogetarou)です。
2つ以上の配列(array)同士を結合して1つの重複なしの配列にする方法を紹介します。
方法

2つ以上の配列(array)同士を重複なしで結合するには、array_unique()とarray_merge()を使います。
まず、array_unique()を呼び出します。
array_unique()の引数でarray_merge()を呼び出します。
そして、array_merge()の引数に結合する配列をカンマ区切りで指定します。
//arr1, arr2, arr3,・・・ = 結合する配列
$result = array_unique(array_merge($arr1, $arr2, arr3, ・・・));
上記のarray_unique()は、array_merge()の引数に指定した全ての配列(array)同士を重複なしで結合し他配列を生成します。
使用例
<?php
$numbers1 = [ "one", "two", "three"];
$numbers2 = ["one", "two", "four"];
$result = array_unique(array_merge($numbers1, $numbers2));
print_r($result)
?>
出力:
Array
(
[0] => one
[1] => two
[2] => three
[5] => four
)
使用例2
<?php
$numbers1 = [ "one", "two", "three"];
$numbers2 = ["one", "two", "six"];
$numbers3 = ["six", "eight", "one"];
$result = array_unique(array_merge($numbers1, $numbers2, $numbers3));
print_r($result)
?>
出力:
Array
(
[0] => one
[1] => two
[2] => three
[5] => six
[7] => eight
)
コメント