如何在 PHP 中使用 array_chunk() 将数组拆分为多个具有平衡项数的数组

问题描述 投票:0回答:0

例如我有这个数组:

$x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];

当我尝试像这样用 array_chunk() 拆分它时:

$arr = [];
// 5 can be changed (dynamic)
foreach (array_chunk($x, 5) as $key => $value){
    $arr[$key] = $value;
    // do somethings
}
dd($arr);

它产生这个数组:

[
    0 => [  1,  2,  3,  4,  5],
    1 => [  6,  7,  8,  9, 10],
    2 => [ 11, 12, 13, 14, 15],
    3 => [ 16, 17]
]

我要的是这个:

[
    0 => [  1,  2,  3,  4,  5],
    1 => [  6,  7,  8,  9],
    2 => [ 10, 11, 12, 13],
    3 => [ 14, 15, 16, 17]
]

有人知道怎么做吗?

php arrays multidimensional-array foreach
© www.soinside.com 2019 - 2024. All rights reserved.