phpの配列について4
phpの関数について使い方等を調べたので記載いたします。
array_merge
array_mergeについて基本的な説明は以前の記事をご覧ください。
keyの指定があった場合の結果は以下になります。
$temp1 = array( "A" => "a", "B" => "c", "C" => "c", "D" => "d", "E" => "a" ); $temp2 = array( "F" => "green", "G" => "red", "H" => "green", "I" => "blue", "J" => "red" ); $temp3 = array_merge($temp1, $temp2); print_r($temp3);
実行結果
Array ( [A] => a [B] => c [C] => c [D] => d [E] => a [F] => green [G] => red [H] => green [I] => blue [J] => red )
2つの配列のkeyが重複していた場合は以下のようになります。
$temp1 = array( "A" => "a", "B" => "c", "C" => "c", "D" => "d", "E" => "a" ); $temp2 = array( "A" => "green", "G" => "red", "B" => "green", "I" => "blue", "C" => "red" ); $temp3 = array_merge($temp1, $temp2); print_r($temp3);
実行結果
Array ( [A] => green [B] => green [C] => red [D] => d [E] => a [G] => red [I] => blue )
重複している配列に関して第二引数の$temp2が上書きしています。
+演算子での結合
ちなみに+演算子で配列を結合した場合は以下のようになります。
$temp1 = array( "A" => "a", "B" => "c", "C" => "c", "D" => "d", "E" => "a" ); $temp2 = array( "F" => "green", "G" => "red", "H" => "green", "I" => "blue", "J" => "red" ); $temp3 = $temp1 + $temp2; print_r($temp3);
実行結果
Array ( [A] => a [B] => c [C] => c [D] => d [E] => a [F] => green [G] => red [H] => green [I] => blue [J] => red )
そしてkeyが重複している場合は以下のようになります。
$temp1 = array( "A" => "a", "B" => "c", "C" => "c", "D" => "d", "E" => "a" ); $temp2 = array( "A" => "green", "G" => "red", "B" => "green", "I" => "blue", "C" => "red" ); $temp3 = $temp1 + $temp2; print_r($temp3);
実行結果
Array ( [A] => a [B] => c [C] => c [D] => d [E] => a [G] => red [I] => blue )
$temp1 が優先されます。
以上になります。