php - How to efficiently merge and possibly convolute two arrays? -
suppose, have 3 arrays:
$a = [ 1, 2, 3 ]; // victim #1 $b = [ 4, 5, 6, 7, 8]; // victim #2 $result = []; // result i need merge $a , $b in such order, each element of $a array should followed element of array $b. elements of $b array, however, might follow each other.
for example:
1 4 2 5 6 3 7 8 i have tried this:
while($a || $b) { $bool = rand(1, 100) >= 50; if($a) { $result[] = array_shift($a); } if($b) { $result[] = array_shift($b); } if($bool && $b) { $result[] = array_shift($b); } } which gives desired output:
array ( [0] => 1 [1] => 4 [2] => 5 [3] => 2 [4] => 6 [5] => 7 [6] => 3 [7] => 8 ) however, think might inefficient because of array_shift()s , if()s appears times there.
question: is there more efficient way that?
p.s.: thanks, know how use array_merge(). not rtm issue.
foreach ($a $value) { $result[] = $value; { $bool = rand(0,1) == 1; $result[] = array_shift($b); } while ($bool); } // insert remaining of value $b in $result foreach ($b $value) $result[] = $value;
Comments
Post a Comment