387   PHP

一,使用 + 运算符

无论是数字键名还是字符串键名,数组合并都是追加,如果出现相同键名,则保留原来的键名和值,新的值将会抛弃;

1,实例代码:

// 字符串键名
$arr1=array(
	'one'=>1,
	'two'=>2,
	'three'=>3
	);
$arr2=array(
	'two'=>'two',
	'three'=>'three',
	'four' => 'four'
	);

var_dump($arr1+$arr2);

// 数字键名
$arr3=array(
	1=>1,
	2=>2,
	3=>3
	);
$arr4=array(
	2=>'two',
	3=>'three',
	4 => 'four'
	);

var_dump($arr3+$arr4);

 

 

2,结果显示:

chenyunhui@ubuntu:/mnt/hgfs/ShareFolder/web/test$ php test.php
array(4) {
  ["one"]=>
  int(1)
  ["two"]=>
  int(2)
  ["three"]=>
  int(3)
  ["four"]=>
  string(4) "four"
}
array(4) {
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [4]=>
  string(4) "four"
}

 

二,使用 array_merge()

 

如果是数字键名,则所有值保留,键名重新排序;如果是字符串键名,遇到相同的键名,新的值将会覆盖原来的值;
1,示例代码:

// 字符串键名
$arr1=array(
	'one'=>1,
	'two'=>2,
	'three'=>3
	);
$arr2=array(
	'two'=>'two',
	'three'=>'three',
	'four' => 'four'
	);

var_dump(array_merge($arr1,$arr2));

// 数字键名
$arr3=array(
	1=>1,
	2=>2,
	3=>3
	);
$arr4=array(
	2=>'two',
	3=>'three',
	4 => 'four'
	);

var_dump(array_merge($arr3,$arr4));


 

结果显示:

chenyunhui@ubuntu:/mnt/hgfs/ShareFolder/web/test$ php test.php
array(4) {
  ["one"]=>
  int(1)
  ["two"]=>
  string(3) "two"
  ["three"]=>
  string(5) "three"
  ["four"]=>
  string(4) "four"
}
array(6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  string(3) "two"
  [4]=>
  string(5) "three"
  [5]=>
  string(4) "four"
}

 

 

三,使用array_merge_recursive()

 

如果是数字键名,则所有值保留,键名重新排序;如果是字符串键名,遇到相同的键名,旧的值和新的值将会合并成一个数组;

1,示例代码:

// 字符串键名
$arr1=array(
	'one'=>1,
	'two'=>2,
	'three'=>3
	);
$arr2=array(
	'two'=>'two',
	'three'=>'three',
	'four' => 'four'
	);

var_dump(array_merge_recursive($arr1,$arr2));

// 数字键名
$arr3=array(
	1=>1,
	2=>2,
	3=>3
	);
$arr4=array(
	2=>'two',
	3=>'three',
	4 => 'four'
	);

var_dump(array_merge_recursive($arr3,$arr4));

 

显示结果:

chenyunhui@ubuntu:/mnt/hgfs/ShareFolder/web/test$ php test.php
array(4) {
  ["one"]=>
  int(1)
  ["two"]=>
  array(2) {
    [0]=>
    int(2)
    [1]=>
    string(3) "two"
  }
  ["three"]=>
  array(2) {
    [0]=>
    int(3)
    [1]=>
    string(5) "three"
  }
  ["four"]=>
  string(4) "four"
}
array(6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  string(3) "two"
  [4]=>
  string(5) "three"
  [5]=>
  string(4) "four"
}




Leave a Reply

Your email address will not be published. Required fields are marked *