数组过滤并合并 php

Array filter and merge in php

我正在尝试合并数组,但没有得到预期结果。

我确实喜欢那样,但没有达到我想要的效果。

$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');

注:不是排序顺序。我想交替排序。

使用array_shift然后每次取第一个元素。最后用 array_filter:

过滤空的 sopts
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');

参考:array-filter, array-shift

实例:3v4l

如果你想让它们排序,就这样做:

print_r(sort(array_merge($a,$b)));    
$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);

我找到了我想要的解决方案。

$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