php - 将数组分成相等的部分,每个数组最多 6 个项目
问题描述
我正在尝试将一个项目数组拆分为多个相等的部分,每个数组最多 6 个项目
例如:
5 items in original array --> result: 1 array with 5 items
12 items in original array --> result: 2 arrays with 6 items
7 items in original array --> result: 2 arrays with 3 and 4 items
13 items in original array --> result: 3 arrays with 5,4,4 items
我完全不知道如何开始
解决方案
我想这就是你要找的。不完全漂亮,但工作:
<?php
$size = 13;
$step = 6;
$input = array_keys(array_fill(0, $size, null));
$count = ceil($size / $step);
$chunk = floor($size / $count);
$bonus = $size % $count;
for ($i = 0; $i < $count; $i++) {
$output[] =
$i == 0 ?
array_slice($input, $i * $chunk, $chunk + $bonus) :
array_slice($input, $i * $chunk + $bonus, $chunk);
}
print_r($output);
这$size
是您的数组$step
的大小,并且是从该数组中切出的块的大小。您可以使用这些值。
具有上述设置的示例输出将是:
Array
(
[0] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
)
[1] => Array
(
[0] => 5
[1] => 6
[2] => 7
[3] => 8
)
[2] => Array
(
[0] => 9
[1] => 10
[2] => 11
[3] => 12
)
)
推荐阅读
- javascript - 如果使用 map() 渲染,如何从子组件更改父组件的状态
- reactjs - react-google-maps 可以使用图像地图类型吗?
- jsf - CDI bean 在 glassfish 5 build 25 中导致 javax.el.PropertyNotFoundException
- python - 矩阵a为二维矩阵,b为三维矩阵时,matmul函数如何理解?
- python - 如何检查数据框是否包含python中的字符串?
- haskell - 为什么'head'(来自前奏包)没有用Maybe以安全的方式实现?
- angular - 如何修复角度 6 中的静态喷射器错误?
- scheme - 当条件为假时,`when` 返回什么?
- c# - Xamarin HybridWebView 导航到缓存文件夹中的页面
- java - setValue 后的不同值