标签:style blog http color io os ar 使用 strong
在数组合并的时候能够使用两个函数 “+”和“array_merge()”
PHP中两个数组合并可以使用+或者array_merge,但之间还是有区别的,而且这些区别如果了解不清楚项目中会要命的!
主要区别是两个或者多个数组中如果出现相同键名,键名分为字符串或者数字,需要注意
1)键名为数字时,array_merge()后面的值将不会覆盖原来的值,而是附加到后面,但+合并数组则会把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉(不是覆盖)
2)键名为字符串时,array_merge()此时会覆盖掉前面相同键名的值,但+仍然把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉(不是覆盖)。
需要注意的是数组键形式 ‘数字‘ 等价于 数字
01 |
$a = array ( ‘a‘ , ‘b‘ ); |
02 |
$b = array ( ‘c‘ , ‘d‘ ); |
03 |
$c = $a + $b ; |
04 |
var_dump( $a ); |
05 |
var_dump( array_merge ( $a , $b )); |
06 |
07 |
//输出: |
08 |
09 |
array |
10 |
0 => string ‘a‘ (length=1) |
11 |
1 => string ‘b‘ (length=1) |
12 |
13 |
array |
14 |
0 => string ‘a‘ (length=1) |
15 |
1 => string ‘b‘ (length=1) |
16 |
2 => string ‘c‘ (length=1) |
17 |
3 => string ‘d‘ (length=1) |
18 |
19 |
++++++++++++++++++++++++++++++++++++++++++ |
20 |
|
21 |
$a = array ( |
22 |
0 => ‘a‘ , |
23 |
1 => ‘b‘ |
24 |
); |
25 |
$b = array ( |
26 |
0 => ‘c‘ , |
27 |
1 => ‘b‘ |
28 |
); |
29 |
$c = $a + $b ; |
30 |
var_dump( $c ); |
31 |
var_dump( array_merge ( $a , $b )); |
32 |
33 |
//输出: |
34 |
35 |
array |
36 |
0 => string ‘a‘ (length=1) |
37 |
1 => string ‘b‘ (length=1) |
38 |
39 |
array |
40 |
0 => string ‘a‘ (length=1) |
41 |
1 => string ‘b‘ (length=1) |
42 |
2 => string ‘c‘ (length=1) |
43 |
3 => string ‘b‘ (length=1) |
44 |
45 |
++++++++++++++++++++++++++++++++++++++++++ |
46 |
47 |
$a = array ( ‘a‘ , ‘b‘ ); |
48 |
$b = array ( |
49 |
‘0‘ => ‘c‘ , |
50 |
1 => ‘b‘ |
51 |
); |
52 |
$c = $a + $b ; |
53 |
var_dump( $c ); |
54 |
var_dump( array_merge ( $a , $b )); |
55 |
56 |
//输出: |
57 |
array |
58 |
0 => string ‘a‘ (length=1) |
59 |
1 => string ‘b‘ (length=1) |
60 |
61 |
array |
62 |
0 => string ‘a‘ (length=1) |
63 |
1 => string ‘b‘ (length=1) |
64 |
2 => string ‘c‘ (length=1) |
65 |
3 => string ‘b‘ (length=1) |
66 |
67 |
++++++++++++++++++++++++++++++++++++++++++ |
68 |
69 |
$a = array ( |
70 |
0 => ‘a‘ , |
71 |
1 => ‘b‘ |
72 |
); |
73 |
$b = array ( |
74 |
‘0‘ => ‘c‘ , |
75 |
‘1‘ => ‘b‘ |
76 |
); |
77 |
$c = $a + $b ; |
78 |
var_dump( $c ); |
79 |
var_dump( array_merge ( $a , $b )); |
80 |
81 |
输出: |
82 |
83 |
array |
84 |
0 => string ‘a‘ (length=1) |
85 |
1 => string ‘b‘ (length=1) |
86 |
87 |
array |
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 )); |
标签:style blog http color io os ar 使用 strong
原文地址:http://www.cnblogs.com/zl-zl/p/4043694.html