PHP中两个数组合并可以使用+或者array_merge,但之间还是有区别的,而且这些区别如果了解不清楚项目中会要命的!
主要区别是两个或者多个数组中如果出现相同键名,键名分为字符串或者数字,需要注意
1)键名为数字时,array_merge()后面的值将不会覆盖原来的值,而是附加到后面,但+合并数组则会把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉(不是覆盖)
2)键名为字符串时,array_merge()此时会覆盖掉前面相同键名的值,但+仍然把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉(不是覆盖)。
需要注意的是数组键形式 '数字' 等价于 数字
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
$a = array ( 'a' , 'b' ); $b = array ( 'c' , 'd' ); $c = $a + $b ; var_dump( $a ); var_dump( array_merge ( $a , $b )); //输出: array 0 => string 'a' (length=1) 1 => string 'b' (length=1) array 0 => string 'a' (length=1) 1 => string 'b' (length=1) 2 => string 'c' (length=1) 3 => string 'd' (length=1) ++++++++++++++++++++++++++++++++++++++++++ $a = array ( 0 => 'a' , 1 => 'b' ); $b = array ( 0 => 'c' , 1 => 'b' ); $c = $a + $b ; var_dump( $c ); var_dump( array_merge ( $a , $b )); //输出: array 0 => string 'a' (length=1) 1 => string 'b' (length=1) array 0 => string 'a' (length=1) 1 => string 'b' (length=1) 2 => string 'c' (length=1) 3 => string 'b' (length=1) ++++++++++++++++++++++++++++++++++++++++++ $a = array ( 'a' , 'b' ); $b = array ( '0' => 'c' , 1 => 'b' ); $c = $a + $b ; var_dump( $c ); var_dump( array_merge ( $a , $b )); //输出: array 0 => string 'a' (length=1) 1 => string 'b' (length=1) array 0 => string 'a' (length=1) 1 => string 'b' (length=1) 2 => string 'c' (length=1) 3 => string 'b' (length=1) ++++++++++++++++++++++++++++++++++++++++++ $a = array ( 0 => 'a' , 1 => 'b' ); $b = array ( '0' => 'c' , '1' => 'b' ); $c = $a + $b ; var_dump( $c ); var_dump( array_merge ( $a , $b )); 输出: array 0 => string 'a' (length=1) 1 => string 'b' (length=1) array 0 => string 'a' (length=1) 1 => string 'b' (length=1) 2 => string 'c' (length=1) 3 => string 'b' (length=1) |
对多个数组合并去重技巧
1
2
3
4
|
$a = array ( '1001' , '1002' ); $b = array ( '1002' , '1003' , '1004' ); $c = array ( '1003' , '1004' , '1005' ); $d = count ( array_flip ( $a ) + array_flip ( $b ) + array_flip ( $c )); |
http://www.awaimai.com/2078.html