如何在忽略键的情况下组合两个PHP数组


How to combine two PHP arrays while ignoring keys

本以为这很容易,但在谷歌上搜索了一段时间后,我发现了不足。我需要组合两个PHP数组,同时忽略键:

array(
  0 => 'Word 1',
  1 => 'Word 2'
)
array(
  0 => 'Word 3',
  1 => 'Word 4',
  2 => 'Word 5'
)

结果应该是:

array(
  0 => 'Word 1',
  1 => 'Word 2',
  2 => 'Word 3',
  3 => 'Word 4',
  4 => 'Word 5'
)

已尝试array_merge,但它替换了重复的密钥。array_combine不起作用,因为它在两个数组中都需要相同数量的元素。

array_merge应该能做到这一点。如果不是,则意味着您的键可能不是数字键。请先尝试将它们转换为基于纯值的数组,然后合并它们。

array_merge(array_values($a), array_values($b))

应该做这个把戏。

样品:https://3v4l.org/chuXV

array_values:http://php.net/manual/en/function.array-values.php

由于PHP 7.4,使用...运算符也是可能的。

$arr1 = ['a', 'b', 'c'];
$arr2 = ['d', 'e', 'f'];
return [...$arr1,  ...$arr2]; // ['a', 'b', 'c', 'd', 'e', 'f']
//Try using two for loops to copy the data over to a third array like this.   
<?php
       $a1 = array(
         0 => 'w1', 
         1 => 'w2'
       );
       $a2 = array(
         0 => 'w3', 
         1 => 'w4', 
         2 => 'w5'
       );

      $counter = 0;
      for($i = 0; $i < count($a1); $i++){
        $a3[$counter] = $a1[$i];
        $counter++;
      }
      for($i = 0; $i < count($a2); $i++){
        $a3[$counter] = $a2[$i];
        $counter++;
      }
      print_r($a3);
?>