我有 2 个数组 -
$a = (1,3,5,7,9);
$b = (2,4,6,8,10);
如何组合这些数组以获得如下结果:
$c = (1,2,3,4,5,6,7,8,9,10);
<?php
$a = array(1,3,5,7,9);
$b = array(2,4,6,8,10);
$c = array_merge($a, $b);
sort($c);
var_dump($c);
印刷:
array(10) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
[5]=>
int(6)
[6]=>
int(7)
[7]=>
int(8)
[8]=>
int(9)
[9]=>
int(10)
}
试试这个你会得到合并的排序数组..
<?php
$array1 = array(1,3,5,7,9);
$array2 = array(2,4,6,8,10);
$result = array_merge($array1, $array2);
sort($result);
print_r($result);
?>
还有一个数组添加运算符,其作用类似于上述array_merge函数:
<?php
$a = array(1,3,5,7,9);
$b = array(2,4,6,8,10);
$c = $a + $b;
sort($c);
var_dump($c);
假设您不能简单地在合并后对值进行排序,因为它们没有自然顺序,这是我知道 PHP 技巧的方式:
$c = call_user_func_array('array_merge', array_map(null, $a, $b));
这是无聊,理智的方式:
$c = array();
foreach ($a as $i => $value) {
$c[] = $value;
$c[] = $b[$i];
}
简单地array_merge
做所有这些工作
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
来源: http: //php.net/manual/en/function.array-merge.php#example-4915