【问题标题】:Array filter and merge in phpphp中的数组过滤和合并
【发布时间】:2023-03-15 19:02:01
【问题描述】:

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

我确实喜欢这样做,但它没有达到我想要的成功。

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

注意:它不是排序顺序。我想排序。

【问题讨论】:

  • 合并后数据是否应该排序?
  • 你不想要第二个数组的'2'和'4'?为什么不能使用array_merge和asort()?
  • 实际的问题是你想要对结果进行排序还是每次从每个数组中添加一个元素?如果你想排序,那么 array_mergesort 按照建议 - 否则请参阅我的帖子
  • 注意:不是排序。我想按其他方式排序。

标签: php arrays array-merge array-filter


【解决方案1】:

使用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-filterarray-shift

现场示例:3v4l

如果您希望它们排序,请执行以下操作:

print_r(sort(array_merge($a,$b)));    

【讨论】:

  • array_values 将删除空数组 print_r(array_values(array_filter($res))); // contains: array('1','2','3','5','6','7','9');
  • 您的回答是最简单的方法,而且比我的回答更好。非常感谢。
【解决方案2】:
$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);

【讨论】:

  • @Drakula Predator 帖子中没有的这个答案有什么新内容?
  • 现在几乎什么都没有,但他的帖子稍后会被编辑以添加排序功能
【解决方案3】:

我得到了我想做的解决方案。

$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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    相关资源
    最近更新 更多