如何在PHP中合并多个数组但将值混合在一起 - 保留它们的顺序

如何在PHP中合并多个数组但将值混合在一起 - 保留它们的顺序

问题描述:

Is there a straightforward way in PHP to combine multiple arrays together but respect the relative order of the elements?

So for example if I had two arrays

$x = ('1','2','3','4');

and

$y = array('a','b','c','d','e');

and I wanted combine them into a single array

$z = ('1','a','2','b','3','c','4','d','e');

Is there a straightforward way of doing this? The ideal solution would also account for different lengths of arrays, behaving as my example does.

array_merge doesn't seem to achieve what I want as it just appends one array to the other.

My current solution loops through each array in order and pushes values to my $z array. This is not only inelegant, it also requires the input arrays to have the same number of values, which isn't ideal for my application.

Any insight would be appreciated

PHP中是否有一种简单的方法将多个数组组合在一起但尊重元素的相对顺序? p>

例如,如果我有两个数组 p>

  $ x =('1','2','3','  4'); 
  code>  pre> 
 
 

和 p>

  $ y = array('a','b','  c','d','e'); 
  code>  pre> 
 
 

我希望将它们组合成一个数组 p>

  $ z =('1','a','2','b','3','c','4','d','e'); 
  code>  
 
 

有这么简单的方法吗? 理想的解决方案也可以解释不同长度的数组,就像我的例子一样。 p>

array_merge似乎没有达到我想要的效果,因为它只是将一个数组附加到另​​一个数组。 p>

我当前的解决方案按顺序遍历每个数组并将值推送到我的$ z数组。 这不仅不优雅,还要求输入数组具有相同数量的值,这对我的应用程序来说并不理想。 p>

任何见解都将受到赞赏 p> div>

You could use this generic function, which can accept any number of arrays, and will output an array with the elements taken from the first "column" first, then from the second, etc:

function mix_merge(...$args) {
    return call_user_func_array('array_merge', 
        array_map(function($i) use ($args) { return array_column($args, $i); },
                  range(0, max(array_map('count', $args))-1)));
}


// Sample data:
$x = array('1','2','3','4');
$y = array('a','b','c','d','e');    
$z = array('A','B','C');    

$res = mix_merge($x, $y, $z);

Result array will be:

['1', 'a', 'A', '2', 'b', 'B', '3', 'c', 'C', '4', 'd', 'e']

Iterate from 0 to the greater length of the two arrays. At each step, if array $x contains item at index, push it to final array $z. Do the same for array $y.

I think this should work -

$count = max(count($x), count($y));

$newArr = array();
for ($i = 0; $i < $count; $i++) {
  // enter values to the new array based on key
  foreach(array($x, $y) as $arr) {
    if (isset($arr[$i])) {
      $newArr[] = $arr[$i];
    }
  }
}

var_dump($newArr);

You can also try this

$x = array('1','2','3','4');
$y = array('a','b','c','d','e');
foreach($y as $key=>$value){
    if($x[$key]){
     $z[] = $x[$key];
     $z[] =     $value;

    }else {
        $z[] = $value;      
    }
}