What would be an elegant way to merge two arrays, so that the resulting array has two elements from the first array, followed by one element from the second array, repeated in this way?
array 1 = A1, A2, A3, A4, A5, etc.
array 2 = B1, B2, B3, B4, B5, etc.
result = A1, A2, B1, A3, A4, B2, A5, A6, B3, etc.
I am trying to do this using a for loop with multiple counters, but I do not know that the lengths of the arrays will always be as long or short as required. I'm curious: is there a better way?
Here is a simplified version of what I'm doing now:
$x = 0, $y = 0;
for($i=0; $i<$total_num_blocks; $i++) {
if ($i % 3) { // if there a remainder, it not an 'every 3rd' item
$result[$i] = $projects[$x++];
} else {
$result[$i] = $posts[$y++];
}
}
source
share