Reputation: 10348
Is there a neat way to split an array into chunks based on an array of lengths?
Input:
$start = range(0, 30);
$length = [3, 7, 2, 12, 6];
Desired Output:
[
[0, 1, 2], // 3
[4, 5, 6, 7, 8, 9, 10], // 7
[11, 12], // 2
[13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24], // 12
[25, 26, 27, 28, 29, 30], // 6
];
Upvotes: 1
Views: 2318
Reputation: 16905
Using array_splice
:
$target = array(); // or use [] in PHP 5.4
foreach($length as $i) {
$target[] = array_splice($start, 0, $i);
}
Be advised, this changes $start
!
Upvotes: 6
Reputation: 4321
This is very easily accomplished with the following:
$target = array();
$offset = 0;
foreach ($length as $lengthValue) {
$target[] = array_slice($start, $offset, $lengthValue);
$offset += $lengthValue;
}
var_dump($target);
What you are doing here is using the array_slice()
method (very similar to the substr
) to extract the portion of the array and then inserting it into the target array. Incrementing the offset each time allows the function to remember which one to use next time.
Upvotes: 2