Home > php教程 > php手册 > body text

php中数组合并操作

WBOY
Release: 2016-06-13 10:03:31
Original
1058 people have browsed it

将多个数组合并起来
1.合并数组
array_merge()函数将数组合并到一起,返回一个联合的数组。所得到的数组以第一个输入数组参数开始,按后面数组参数出现的顺序依次迫加。其形式为:


view sourceprint?1 array array_merge (array array1 array2…,arrayn)


 

将一个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。
如果输入的数组中有相同的字符串键名,则该键名后面的值将覆盖前一个值。然而,如果数组包含数字键名,后面的值将不会覆盖原来的值,而是附加到后面。
如果只给了一个数组并且该数组是数字索引的,则键名会以连续方式重新索引。
实例如下:


view sourceprint?1 $face = array("j","q","k","a"); 

2 $numbered = array("2","3","4","5","6","7","8","9"); 

3 $cards = array_merge($face, $numbered); 

4 shuffle($cards); 

5 print_r($cards);


 

这将返回如下所示的结果,运行代码:


view sourceprint?array ( [0] => a [1] => 4 [2] => 9 [3] => 3 [4] => k [5] => 7 [6] => 5 [7] => q [8] => 6 [9] => 8 [10] => 2 [11] => j )


 

 

2.递归追加数组
array_merge_recursive()函数与array_merge()相同,可以将两个或多个数组合并在一起,形成一个联合的数组.两者之间的区别在于,当某个输入数组中的某个键己经存在于结果数组中时该函数会采取不同的处理方式.array_merge()会覆盖前面存在的键/值对,替换为当前输入数组中的键/值对,而array_merge_recursive()将把两个值合并在一起,形成一个新的数组,并以原有的键作为数组名。还有一个数组合并的形式,就是递归追加数组。其形式为:


view sourceprint?array array_merge_recursive( array key,array values )


 

示例如下:


view sourceprint?1 $class1 = array("john" => 100, "james" => 85); 

2 $class2 = array("micky" => 78, "john" => 45); 

3 $classscores = array_merge_recursive($class1, $class2); 

4 print_r($classscores);


 

这将返回如下结果:


view sourceprint?array ( [john] => array ( [0] => 100 [1] => 45 ) [james] => 85 [micky] => 78 )


 

 

3.连接两个数组
array_combine()函数会得到一个新数组,它由一组提交的键和对应的值组成。其形式为:


view sourceprint?array array_merge(array array1,array array2[…,array arrayn])


 

注意,两个输入数组必须大小相同,不能为空。示例如下:


view sourceprint?1 $abbreviations = array("al","ak","az","ar"); 

2 $states = array("alabama","alaska","arizona","arkansas"); 

3 $statemap = array_combine($abbreviations,$states); 

4 print_r($statemap);


 

这会返回:


view sourceprint?1 array ( [al] => alabama [ak] => alaska [az] => arizona [ar] => arkansas )

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template