我正在尝试合并数组,但没有达到我的期望。
我确实喜欢那样,但是我想要的并不成功。
$a = array('1', '3', '5', '7', '9');
$b = array('2', '4', '6');
$count_b = sizeof($b);
$i = 0;
while ($i < $count_b){
$a_b[] = $a[$i];
$a_b[] = $b[$i];
$i++;
}
// the result will be
$a_b = array('1','2','3','4','5','6');
我的问题是我不知道要合并丢失的'7'和'9'数组。
示例:
$a = array('1', '3', '5', '7', '9');
$b = array('2', '4', '6');
预期结果
$c = array('1','2','3','4','5','6','7','9');
注意:它不对顺序进行排序。我想按另一种方式排序。
答案 0 :(得分:1)
使用array_shift
,然后每次取第一个元素。最后用array_filter
过滤空的sopt:
while ($a || $b) {
$res[] = array_shift($a);
$res[] = array_shift($b);
}
print_r(array_filter($res)); // contains: array('1','2','3','5','6','7','9');
实时示例:3v4l
如果要对它们进行排序,请执行以下操作:
print_r(sort(array_merge($a,$b)));
答案 1 :(得分:0)
$a = array('1', '3', '5', '7', '9');
$b = array('2', '4', '6');
$c = array_merge($a, $b);
//If you want to sort array add this line too
//If you want to preserve keys, check asort() function
sort($c);
print_r($c);
答案 2 :(得分:0)
我想解决的办法。
$a = array('1', '3', '5', '7', '9');
$b = array('2', '4', '6');
$count_b = sizeof($b);
$i = 0;
while ($i < $count_b){
$a_b[] = $a[$i];
$a_b[] = $b[$i];
$i++;
}
// the result will be
$a_b = array('1','2','3','4','5','6');
$ab = array_unique(array_merge( $a_b,$a ));
$ab= array_values($ab);
// this is my excepted result
array (size=8)
0 => int 1
1 => int 2
2 => int 3
3 => int 4
4 => int 5
5 => int 6
6 => int 7
7 => int 9