Reputation: 23
I have an array of dynamic length L1. I need to split this array into L2 number of arrays each having LEN[i]
numbers from the original array.
Input arrays:
$array = [1,2,3,4,5,6,7,8,9,10]
$LEN = [3,3,4]
$LEN
states how many elements each new array should contain. The 3 arrays will be:
$a1 = [1,2,3]
$a2 = [4,5,6]
$a3 = [7,8,9,10]
I have tried a lot of ways but nothing seems to be working. Any help would be greatly appreciated.
Upvotes: 2
Views: 8160
Reputation: 1488
Here you go
function SplitLike($array, $groups)
{
$result = [];
$left = count($array);
foreach ($groups as $i => $group) {
$result[$i] = array_slice($array, count($array) - $left, $group);
$left -= $group;
}
return $result;
}
Upvotes: 0
Reputation: 7485
<?php
$input = range(1,11);
$chunk_size = 3;
$output = array_chunk($input, $chunk_size);
// If we can't chunk into equal sized parts merge the last two arrays.
if(count($input) % $chunk_size) {
$leftovers = array_pop($output);
$last = array_pop($output);
array_push($output, array_merge($last, $leftovers));
}
var_export($output);
Output:
array (
0 =>
array (
0 => 1,
1 => 2,
2 => 3,
),
1 =>
array (
0 => 4,
1 => 5,
2 => 6,
),
2 =>
array (
0 => 7,
1 => 8,
2 => 9,
3 => 10,
4 => 11,
),
)
Upvotes: 2
Reputation: 21437
If you need such a variable array length of chunks then you can create your own functionality using simple foreach
and array_splice
like as
$array=[1,2,3,4,5,6,7,8,9,10];
$arr = [3,3,4];
$result_arr = [];
foreach($arr as $k => $v){
$result_arr[$k] = array_splice($array,0,$v);
}
print_R($result_arr);
Output:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 4
[1] => 5
[2] => 6
)
[2] => Array
(
[0] => 7
[1] => 8
[2] => 9
[3] => 10
)
)
Upvotes: 6