想象一下有几个数组结构(我现在有三个,但我希望尽可能灵活)
$array1 = array("red", "red", "red");
$array2 = array("green", "green", "green", "green");
$array3 = array("blue", "blue");
我需要将这些数组合并在一起并具有如下结构:
Array
(
[0] => red
[1] => green
[2] => blue
[3] => red
[4] => green
[5] => blue
[6] => red
[7] => green
[8] => green
)
想法是迭代遍历所有数组并逐个合并元素,如果任何数组的元素用完了,循环应该继续正常,我不确定我是否在这里解释自己最好
答案 0 :(得分:1)
使用count,array_push和循环计数
<?php
$array1 = array("red", "red", "red");
$array2 = array("green", "green", "green", "green");
$array3 = array("blue", "blue");
$ArrayLength = array(count($array1),count($array2),count($array3));
$Arrays= array ( $array1,$array2,$array3 );
$MergeArray=array();
$flag=true;
for($i=0;$flag==true;$i++)
{
$flag=false;
for($j=0;$j < count($ArrayLength) ; j++)
{
if( $i < $ArrayLength[$j] )
{
array_push( $MergeArray , $Arrays[$j][$i] );
$flag=true;
}
}
}
Print_r( $MergeArray );
?>
答案 1 :(得分:0)
我会尝试类似的事情:
$result = array();
$array1 = array("red", "red", "red");
$array2 = array("green", "green", "green", "green");
$array3 = array("blue", "blue");
$arrays = array($array1, $array2, $array3);
$largest = 0;
//Get the largest array
foreach($arrays as $arr):
if(count($arr) > $largest)
$largest = $count;
endforeach;
$current = 0;
while($current <= $largest):
foreach($arrays as $arr):
if(count($arr)>0 && $value = array_pop($arr))
$result[] = $value;
endforeach;
endwhile;
然而,这可能会被重构以提高效率