在数组合并的时候能够使用两个函数 “+”和“array_merge()”
PHP中两个数组合并可以使用+或者array_merge,但之间还是有区别的,而且这些区别如果了解不清楚项目中会要命的!
主要区别是两个或者多个数组中如果出现相同键名,键名分为字符串或者数字,需要注意
1)键名为数字时,array_merge()后面的值将不会覆盖原来的值,而是附加到后面,但+合并数组则会把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉(不是覆盖)
2)键名为字符串时,array_merge()此时会覆盖掉前面相同键名的值,但+仍然把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉(不是覆盖)。
需要注意的是数组键形式 ‘数字‘ 等价于 数字
05 |
var_dump( array_merge ( $a , $b )); |
10 |
0 => string ‘a‘ (length=1) |
11 |
1 => string ‘b‘ (length=1) |
14 |
0 => string ‘a‘ (length=1) |
15 |
1 => string ‘b‘ (length=1) |
16 |
2 => string ‘c‘ (length=1) |
17 |
3 => string ‘d‘ (length=1) |
19 |
++++++++++++++++++++++++++++++++++++++++++ |
31 |
var_dump( array_merge ( $a , $b )); |
36 |
0 => string ‘a‘ (length=1) |
37 |
1 => string ‘b‘ (length=1) |
40 |
0 => string ‘a‘ (length=1) |
41 |
1 => string ‘b‘ (length=1) |
42 |
2 => string ‘c‘ (length=1) |
43 |
3 => string ‘b‘ (length=1) |
45 |
++++++++++++++++++++++++++++++++++++++++++ |
54 |
var_dump( array_merge ( $a , $b )); |
58 |
0 => string ‘a‘ (length=1) |
59 |
1 => string ‘b‘ (length=1) |
62 |
0 => string ‘a‘ (length=1) |
63 |
1 => string ‘b‘ (length=1) |
64 |
2 => string ‘c‘ (length=1) |
65 |
3 => string ‘b‘ (length=1) |
67 |
++++++++++++++++++++++++++++++++++++++++++ |
79 |
var_dump( array_merge ( $a , $b )); |
84 |
0 => string ‘a‘ (length=1) |
85 |
1 => string ‘b‘ (length=1) |
88 |
0 => string ‘a‘ (length=1) |
89 |
1 => string ‘b‘ (length=1) |
90 |
2 => string ‘c‘ (length=1) |
91 |
3 => string ‘b‘ (length=1) |
对多个数组合并去重技巧
1 |
$a = array ( ‘1001‘ , ‘1002‘ ); |
2 |
$b = array ( ‘1002‘ , ‘1003‘ , ‘1004‘ ); |
3 |
$c = array ( ‘1003‘ , ‘1004‘ , ‘1005‘ ); |
4 |
$d = count ( array_flip ( $a ) + array_flip ( $b ) + array_flip ( $c )); |