本文討論PHP合並數組的兩種方式:$a+$b , array_merge($a,$b)
操作符+,在前一個數的基礎上插入後一個數組,如果有相同的拋棄,而array_merge 是在前一個參數基礎上插入後一個參數,如果有相同用的key 用後一個覆蓋。
實例如下:
php > $a = array('a'=>'1','b'=>'2','c'=>'3');
php > $b = array('c'=>3,'d'=>'4','e'=>'5');
php > $c = $a+$b;
php > $d = array_merge($a,$b);
php > var_dump($c,$d);
array(5) {
'a' =>
string(1) "1"
'b' =>
string(1) "2"
'c' =>
string(1) "3"
'd' =>
string(1) "4"
'e' =>
string(1) "5"
}
array(5) {
'a' =>
string(1) "1"
'b' =>
string(1) "2"
'c' =>
int(3)
'd' =>
string(1) "4"
'e' =>
string(1) "5"
}
php > $e = array_merge($b,$a);
php > var_dump($e);
array(5) {
'c' =>
string(1) "3"
'd' =>
string(1) "4"
'e' =>
string(1) "5"
'a' =>
string(1) "1"
'b' =>
string(1) "2"
}
php > $f=$b+$a;
php > var_dump($f);
array(5) {
'c' =>
int(3)
'd' =>
string(1) "4"
'e' =>
string(1) "5"
'a' =>
string(1) "1"
'b' =>
string(1) "2"
}
當兩邊都是索引數組時,使用array_merge 可能會引起索引重置,如下面這種情況:
php > $a = array();
php > $b = array(1=>'data');
php > $c = $a+$b;
php > $d = array_merge($a,$b);
php > var_dump($c,$d);
array(1) {
[1] =>
string(4) "data"
}
array(1) {
[0] =>
string(4) "data"
}
所以,當使用+來合並兩個索引數組,值可能會被丟棄,而array_merge就不會,會把重復的索引重置:
php > $a = array(1=>'one',2=>'two',3=>'three');
php > $b = array(3=>'three',4=>'four',5=>'five');
php > $c = $a+$b;
php > $d = array_merge($a,$b);
php > var_dump($c,$d);
array(5) {
[1] =>
string(3) "one"
[2] =>
string(3) "two"
[3] =>
string(5) "three"
[4] =>
string(4) "four"
[5] =>
string(4) "five"
}
array(6) {
[0] =>
string(3) "one"
[1] =>
string(3) "two"
[2] =>
string(5) "three"
[3] =>
string(5) "three"
[4] =>
string(4) "four"
[5] =>
string(4) "five"
}
CentOS 6.3 安裝LNMP (PHP 5.4,MyySQL5.6) http://www.linuxidc.com/Linux/2013-04/82069.htm
在部署LNMP的時候遇到Nginx啟動失敗的2個問題 http://www.linuxidc.com/Linux/2013-03/81120.htm
Ubuntu安裝Nginx php5-fpm MySQL(LNMP環境搭建) http://www.linuxidc.com/Linux/2012-10/72458.htm
《細說PHP》高清掃描PDF+光盤源碼+全套教學視頻 http://www.linuxidc.com/Linux/2014-03/97536.htm
PHP 的詳細介紹:請點這裡
PHP 的下載地址:請點這裡