Question

Imagine having a few array structures (I present three, but I'd like to be as flexible as possible)

$array1 = array("red", "red", "red");  

$array2 = array("green", "green", "green", "green"); 

$array3 = array("blue", "blue"); 

I need to merge these arrays together and have a structure like so:

Array
(
    [0] => red
    [1] => green
    [2] => blue
    [3] => red
    [4] => green
    [5] => blue
    [6] => red
    [7] => green
    [8] => green
)

The idea is to iterate through all arrays and merge elements one by one, if any of the arrays has run out of elements, the cycle should continue as normal, I'm not sure if I'm explaining myself the best here

Was it helpful?

Solution

using count , array_push , and loop on counts

<?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 );
?>

OTHER TIPS

I would try something like:

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

However this could probably be refactored to be more efficient

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top