我有两个数组:
Array ( [0] => a [1] => b [2] => c [3] => d )
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
我想合并他们,所以他们最终会这样:
Array ( [0] => a [1] => 1 [2] => b [3] => 2 [4] => c [5] => 3 [6] => d [7] => 4 )
类似于数组1 [1],数组2 [1],数组1 [2],数组2 [2]等等。
这可能很简单但我无法在任何地方找到答案!
答案 0 :(得分:1)
根据最长数组的长度,你必须使用一个循环。
// 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 );
结果:
Array ( [0] => 1 [1] => a [2] => 2 [3] => b [4] => 3 [5] => c [6] => 4 [7] => d )
在此PHP Fiddle中运行。