4

想象一下有几个数组结构(我展示了三个,但我希望尽可能灵活)

$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
)

这个想法是遍历所有数组并一个一个地合并元素,如果任何一个数组已经用完元素,循环应该正常继续,我不确定我是否在这里解释自己最好

4

2 回答 2

2

使用 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 );
?>
于 2013-09-01T20:44:40.860 回答
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;

然而,这可能会被重构为更有效

于 2013-09-01T21:04:22.870 回答