首页 > 解决方案 > 将数组分成相等的部分,每个数组最多 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

解决方案


我想这就是你要找的。不完全漂亮,但工作:

<?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
        )
)

推荐阅读