合並數據在php中我們利用array_merge()函數來實現,array_merge() 函數把兩個或多個數組合並為一個數組。 如果鍵名有重復,該鍵的鍵值為最後一個鍵名對應的值(後面的覆蓋前面的)。如果數組是數字索引的,則鍵名會以連續方式重新索引。 代碼如下 復制代碼
<?php
echo "rn第一種情況rn";
$a=array(1,2,3,4,5,6);
$b=array(7,8,9);
$c=array_merge ($a,$b);
print_r($c);
$c=$a+$b;
print_r($c);
$c=$b+$a;
print_r($c);
echo "rn第二種情況rn";
$a=array('a','b','c','d','e','f');
$b=array('a','x','y');
$c=array_merge ($a,$b);
print_r($c);
$c=$a+$b;
print_r($c);
$c=$b+$a;
print_r($c);
echo "rn第三種情況rn";
$a=array(
1=>'a',
2=>'b',
3=>'c',
4=>'d',
5=>'e',
6=>'f');
$b=array(
1=>'a',
7=>'x',
8=>'y');
$c=array_merge ($a,$b);
print_r($c);
$c=$a+$b;
print_r($c);
$c=$b+$a;
print_r($c);
?>
結果如下:
第一種情況
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
Array
(
[0] => 7
[1] => 8
[2] => 9
[3] => 4
[4] => 5
[5] => 6
)
第二種情況
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
[6] => a
[7] => x
[8] => y
)
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
)
Array
(
[0] => a
[1] => x
[2] => y
[3] => d
[4] => e
[5] => f
)
第三種情況
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
[6] => a
[7] => x
[8] => y
)
Array
(
[1] => a
[2] => b
[3] => c
[4] => d
[5] => e
[6] => f
[7] => x
[8] => y
)
Array
(
[1] => a
[7] => x
[8] => y
[2] => b
[3] => c
[4] => d
[5] => e
[6] => f
)
1)鍵名
為數字時,array_merge()不會覆蓋掉原來的值,但+合並數組則會把最先出現的值作為最終結果返回,而把後面的數組擁有相同鍵名的那些值“拋棄”掉(不是覆蓋)
2)鍵名為字符時,+仍然把最先出現的值作為最終結果返回,而把後面的數組擁有相同鍵名的那些值“拋棄”掉,但array_merge()此時會覆蓋掉前面相同鍵名的值
注釋:如果僅僅向 array_merge() 函數輸入了一個數組,且鍵名是整數,則該函數將返回帶有整數鍵名的新數組,其鍵名以 0 開始進行重新索引