Home > php教程 > php手册 > PHP合并、追加与连接数组

PHP合并、追加与连接数组

WBOY
Release: 2016-06-13 09:38:21
Original
953 people have browsed it

合并数组

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

array array_merge (array array1 array2…,arrayN)
Copy after login

将一个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。

如果输入的数组中有相同的字符串键名,则该键名后面的值将覆盖前一个值。然而,如果数组包含数字键名,后面的值将不会覆盖原来的值,而是附加到后面。

如果只给了一个数组并且该数组是数字索引的,则键名会以连续方式重新索引。

实例如下:

$face = array("J","Q","K","A");
$numbered = array("2","3","4","5","6","7","8","9");
$cards = array_merge($face, $numbered);
shuffle($cards);
print_r($cards);
Copy after login

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

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 )
Copy after login

递归追加数组

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

array array_merge_recursive( array key,array values )
Copy after login

示例如下:

$class1 = array("John" => 100, "James" => 85);
$class2 = array("Micky" => 78, "John" => 45);
$classScores = array_merge_recursive($class1, $class2);
print_r($classScores);
Copy after login

这将返回如下结果:

Array ( [John] => Array ( [0] => 100 [1] => 45 ) [James] => 85 [Micky] => 78 )
Copy after login

连接两个数组

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

array array_merge(array array1,array array2[…,array arrayN])
Copy after login

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

$abbreviations = array("AL","AK","AZ","AR");
$states = array("Alabama","Alaska","Arizona","Arkansas");
$stateMap = array_combine($abbreviations,$states);
print_r($stateMap);
Copy after login

这会返回:

Array ( [AL] => Alabama [AK] => Alaska [AZ] => Arizona [AR] => Arkansas )
Copy after login
Related labels:
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