最近的工作中老是要遇到将两个数组进行拼接的操作。下面总结一下数组拼接的几个函数及它们的不同点。

PHP中两个数组合并可以使用+或者array_merge,但之间还是有区别的,而且这些区别如果了解不清楚项目中会要命的!

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

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

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

总结一句就是,用+拼接时,键名一样时只认先出现的(前任),用array_merge拼接时,键名一样时,分键名为数字还是字符串(看脸),数字时不覆盖,字符串时会覆盖原来的值(字符串比较丑,数字比较漂亮)。

实例:

$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.单数组去重复array_unique($arrTest)

//2.多数组去重复array_keys(array_flip($arr1)+array_flip($arr2))

实例:

$a = array(‘1001′,’1002’);

$b = array(‘1002′,’1003′,’1004’);

$c = array(‘1003′,’1004′,’1005’);

$d = array_keys(array_flip($a) + array_flip($b) + array_flip($c));

var_dump($d);

++++++++++++++++++++++++++++++++++++++++++

//输出:

array(5) { [0]=> int(1001) [1]=> int(1002) [2]=> int(1003) [3]=> int(1004) [4]=> int(1005) }

$c = array(‘1003′,’1004′,’1005′,’1005’);

$e = array_unique($c);

var_dump($e);

++++++++++++++++++++++++++++++++++++++++++

//输出:

array(3) { [0]=> string(4) “1003” [1]=> string(4) “1004” [2]=> string(4) “1005” }

数组拼接也是PHP后台工程师面试经常需要回答的问题,希望我的讲解对大家有帮助。