ChuckKelly ChuckKelly - 6 months ago 14
PHP Question

Merge 2 arrays into one with a balanced 2-1 ratio

I have 2 arrays ....lets call them red_array and blue_array and what I would like to do is create a final_array that has a 1 to 2 ratio of blue_array items to red_array aka

array[]= { BLUE_ARRAY_ITEM , RED_ARRAY_ITEM, RED_ARRAY_ITEM,
BLUE_ARRAY_ITEM,RED_ARRAY_ITEM, RED_ARRAY_ITEM, BLUE_ARRAY_ITEM} ....ect on`


Whats the best way to go about this ?Here is what I started with trying, but all it gives me is a unexpected_token error

$total_count=count($blue_query)+count($red_query);

$count=0;
$blue_count=0;
$red_count=0;
while ($count <= $total_count) {

if($blue_count<=50){
$finished_array[]=$blue_query[$blue_count];
$blue_count++;
$count++;
}

if($red_count<=50){
$finished_array[]=$red_query[$red_count];
$red_count++;
$count++;
$finished_array[]=$red_query[$red_count];

$red_count++;
$count++;
}


}

Answer

Try -

<?php
$blue = array(1,4,7,10);
$red = array(2,3,5,6,8,9);

$final_array = array();

for($i=0; $i<sizeof($blue); $i++)
{
    if($i < sizeof($blue))
    {
       $final_array[] = $blue[$i];
    }

    if(($i*2) < sizeof($red))
    {
       $final_array[] = $red[$i*2];
       $final_array[] = $red[($i*2)+1];
    }
}

echo '<pre>'; print_r($final_array);


OUTPUT

<pre>Array
(
   [0] => 1
   [1] => 2
   [2] => 3
   [3] => 4
   [4] => 5
   [5] => 6
   [6] => 7
   [7] => 8
   [8] => 9
   [9] => 10
)


DEMO

http://3v4l.org/S4jVS

Comments