PHP按特定顺序合并数组,而不是简单地附加它们

PHP按特定顺序合并数组,而不是简单地附加它们

问题描述:

I have two arrays:

Array ( [0] => a [1] => b [2] => c [3] => d ) 
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )

I want to merge them so they end up like this:

Array ( [0] => a [1] => 1 [2] => b [3] => 2 [4] => c [5] => 3 [6] => d [7] => 4 )

Something like array 1[1], array 2[1], array 1[2], array 2[2], etc.

It's probably simple but I can't find an answer anywhere!

You would have to use a loop as far as I know, based on the length of the longest array.

// input arrays
$array1 = array( 1, 2, 3, 4 );
$array2 = array( 'a', 'b', 'c', 'd' );

// output arrays
$array3 = array();

// get the longest for the loop
$length = count($array1) > count($array2)? count($array1) : count($array2);

// if there is an element set for the index append to the output array
for ( $i=0; $i<$length; $i++ ){
    if ( isset($array1[$i]) ) $array3[] = $array1[$i];
    if ( isset($array2[$i]) ) $array3[] = $array2[$i];
}

print_r( $array3 );

Results in:

Array ( [0] => 1 [1] => a [2] => 2 [3] => b [4] => 3 [5] => c [6] => 4 [7] => d )

Run in this PHP Fiddle.