我有2个数组 -
$a = (1,3,5,7,9);
$b = (2,4,6,8,10);
如何组合这些数组以获得如下结果:
$c = (1,2,3,4,5,6,7,8,9,10);
答案 0 :(得分:4)
<?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)
}
答案 1 :(得分:1)
试试这个你将获得合并的排序数组..
<?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);
?>
答案 2 :(得分:0)
还有一个数组添加运算符,其作用类似于上面提到的 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);
答案 3 :(得分:0)
假设你的不能简单地在合并后对值进行排序,因为它们没有自然顺序,这里是I-know-PHP-tricks方式:
$c = call_user_func_array('array_merge', array_map(null, $a, $b));
这是无聊,理智的方式:
$c = array();
foreach ($a as $i => $value) {
$c[] = $value;
$c[] = $b[$i];
}
答案 4 :(得分:-2)
简单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