I have an array like $array=[1,2,3,4,5,6,7,8,9,10]; and I want to split it as 3,2 length:
$array=[
array(1,2,3),
array(4,5),
array(6,7,8),
array(9,10),
]
How I can solve this problem?
CodePudding user response:
array_splice() can help to grab alternatively 2 or 3 items from your array, and put them in a new array.
$array = array(1,2,3,4,5,6,7,8,9,10);
$out = array();
$step = true;
while (count($array)) {
$out[] = array_splice($array, 0, $step ? 3 : 2);
$step = !$step;
}
$out will be [[1,2,3],[4,5],[6,7,8]...
doc : https://php.net/array_splice
CodePudding user response:
$array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$slices = [3, 2];
$sliced = [];
$i = 0;
while ($i < count($array)) {
foreach ($slices as $length) {
$sliced[] = array_slice($array, $i, $length);
$i = $length;
}
}
print_r($sliced);
