码迷,mamicode.com
首页 > Web开发 > 详细

php 合并数组 "+"和"array_merge"的区别

时间:2014-07-07 00:36:48      阅读:304      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   cti   io   div   

主要区别是两个或者多个数组中如果出现相同键名,键名分为字符串或者数字,需要注意

1)键名为数字时,array_merge()不会覆盖掉原来的值,但+合并数组则会把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉(不是覆盖)

2)键名为字符时,+仍然把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉,但array_merge()此时会覆盖掉前面相同键名的值

 

 

<?php
$array1 = array(0 => ‘zero_a‘, 2 => ‘two_a‘, 3 => ‘three_a‘);
$array2 = array(1 => ‘one_b‘, 3 => ‘three_b‘, 4 => ‘four_b‘);
$result = $array1 + $array2;
var_dump($result);
?>
结果:
array(5) {
  [0]=>
  string(6) "zero_a"
  [2]=>
  string(5) "two_a"
  [3]=>
  string(7) "three_a"
  [1]=>
  string(5) "one_b"
  [4]=>
  string(6) "four_b"
}


<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
 
结果:
Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)


http://www.php.net/manual/zh/function.array-merge.php

另有函数array_merge_recursive()可对比学习。

php 合并数组 "+"和"array_merge"的区别,布布扣,bubuko.com

php 合并数组 "+"和"array_merge"的区别

标签:style   http   color   cti   io   div   

原文地址:http://www.cnblogs.com/eterwei/p/3822268.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!