php合并数组的两种方式

1:+

2:array_merge()函数

加号形式,不管是索引数组还是关联数组,如果出现key一样的时候,以前一个数组的值为准,例如:

$a = array('a'=>'1','b'=>'2','c'=>'3');  
$b = array('c'=>3,'d'=>'4','e'=>'5'); 
$c = $a+$b; 
var_dump($c);

array (size=5)
  'a' =>  '1' (length=1)
  'b' =>  '2' (length=1)
  'c' =>  '3' (length=1)
  'd' =>  '4' (length=1)
  'e' =>  '5' (length=1)
$a = array(1=>'one',2=>'two',3=>'three1');  
$b = array(3=>'three2',4=>'four',5=>'five');  
$c = $a+$b; 
var_dump($c);

array (size=5)
  1 =>  'one' (length=3)
  2 =>  'two' (length=3)
  3 =>  'three1' (length=6)
  4 =>  'four' (length=4)
  5 =>  'five' (length=4)

array_merge()形式,如果是关联数组,key相同的情况下,以后一个数组的值为准(也就是后一个的值会覆盖掉前一个值),如果是索引数组,则不会覆盖,会增加一个key,例如

$a = array('a'=>'1','b'=>'2','c'=>'3');  
$b = array('c'=>3,'d'=>'4','e'=>'5'); 
$d = array_merge($a,$b); 
var_dump($d);

array (size=5)
  'a' =>  '1' (length=1)
  'b' =>  '2' (length=1)
  'c' =>  3
  'd' =>  '4' (length=1)
  'e' =>  '5' (length=1)
$a = array(1=>'one',2=>'two',3=>'three1');  
$b = array(3=>'three2',4=>'four',5=>'five');  
$d = array_merge($a,$b); 
var_dump($d);

array (size=6)
  0 =>  'one' (length=3)
  1 =>  'two' (length=3)
  2 =>  'three1' (length=6)
  3 =>  'three2' (length=6)
  4 =>  'four' (length=4)
  5 =>  'five' (length=4)

你可能感兴趣的:(php)