I've extended @Glavić's excellent, excellent looped array injection script to provide greater control of the frequency of insertion and the amount of data per insertion.
This script is designed to work with non-negative parameters. The input arrays may be of any length with no requirement to share the same length. The first array is modified to become the result array, so if you need to preserve its initial data, you'll need to save a copy before iterating.
Have a play by modifying the arrays, $afterEvery
, and $insertCount
in the 3v4l.org demo link.
Code: (Demo)
$a = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9'];
$b = ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B9'];
$afterEvery = 2;
$insertCount = 1;
for ($i = 0, $count = count($b); $i < $count; ++$i) {
array_splice(
$a, # the array to be modified
$afterEvery + $afterEvery * $i + $insertCount * $i, # each iteration must account for previously inserted elements
0, # do not consume any elements from $a
array_slice($b, $i * $insertCount, $insertCount) # push array of element(s) into $a
);
}
var_export($a);
Cases with arithmetic breakdown:
/*
insert 2 after every 1 every + (every * i) + (insert * i)
0 (insert @ 1) ... A B B A A A A A A A A A A 1 + (1 * 0) + (2 * 0) = 1
1 (insert @ 4) ... A B B A B B A A A A A A A 1 + (1 * 1) + (2 * 1) = 4
2 (insert @ 7) ... A B B A B B A B B A A A A 1 + (1 * 2) + (2 * 2) = 7
3 (insert @ 10) ... A B B A B B A B B A B B A 1 + (1 * 3) + (2 * 3) = 10
*/
/*
insert 1 after every 2 every + (every * i) + (insert * i)
0 (insert @ 2) ... A A B A A A A A A A A A A 2 + (2 * 0) + (1 * 0) = 2
1 (insert @ 5) ... A A B A A B A A A A A A A 2 + (2 * 1) + (1 * 1) = 5
2 (insert @ 8) ... A A B A A B A A B A A A A 2 + (2 * 2) + (1 * 2) = 8
3 (insert @ 11) ... A A B A A B A A B A A B A 2 + (2 * 3) + (1 * 3) = 11
*/
/*
insert 1 after every 3 every + (every * i) + (insert * i)
0 (insert @ 3) ... A A A B A A A A A A A A A 3 + (3 * 0) + (1 * 0) = 3
1 (insert @ 7) ... A A A B A A A B A A A A A 3 + (3 * 1) + (1 * 1) = 7
2 (insert @ 11) ... A A A B A A A B A A A B A 3 + (3 * 2) + (1 * 2) = 11
3 (insert @ 15) ... A A A B A A A B A A A B A 3 + (3 * 3) + (1 * 3) = 15
*/
/*
insert 3 after every 2 every + (every * i) + (insert * i)
0 (insert @ 2) ... A A B B B A A A A A A A A 2 + (2 * 0) + (3 * 0) = 2
1 (insert @ 7) ... A A B B B A A B B B A A A 2 + (2 * 1) + (3 * 1) = 7
2 (insert @ 12) ... A A B B B A A B B B A A B 2 + (2 * 2) + (3 * 2) = 12
3 (insert @ 17) ... A A B B B A A B B B A A B 2 + (2 * 3) + (3 * 3) = 17
*/