我有一个动态长度为L1的数组。我需要将此数组拆分为L2数组,每个数组都包含原始数组中的LEN[i]
个数字。
EX:
Original:
$array=[1,2,3,4,5,6,7,8,9,10]
Here L1=10
L2=3
$LEN=[3,3,4]
So the 3 arrays will be
$a1=[1,2,3]
$a2=[4,5,6]
$a3=[7,8,9,10]
我尝试了很多方法,但似乎没有任何工作。 任何帮助将不胜感激。
答案 0 :(得分:4)
如果您需要这样一个可变数组长度的块,那么您可以使用简单的foreach
和array_splice
创建自己的功能,如
$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);
<强>输出:强>
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
)
)
答案 1 :(得分:1)
<?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);
输出:
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,
),
)