将数组拆分为 N 个数组 - PHP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15579702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:30:43  来源:igfitidea点击:

Split an Array into N Arrays - PHP

phparraysmultidimensional-arraysplit

提问by Daniel Harris

I have an array of 18 values:

我有一个包含 18 个值的数组:

$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r');

I want to split this array into 12 different arrays so it should look like this:

我想将此数组拆分为 12 个不同的数组,因此它应该如下所示:

array(
    0 => array('a', 'b'),
    1 => array('c', 'd'),
    2 => array('e', 'f'),
    3 => array('g', 'h'),
    4 => array('i', 'j'),
    5 => array('k', 'l'),
    6 => array('m'),
    7 => array('n'),
    8 => array('o'),
    9 => array('p'),
   10 => array('q'),
   11 => array('r')
)

My function doesn't seem to work

我的功能似乎不起作用

function array_split($array, $parts){
    return array_chunk($array, ceil(count($array) / $parts));
}

$result = array_split($array, 12);

because I get 9 different arrays instead of 12. It would return

因为我得到 9 个不同的数组而不是 12 个。它会返回

array(
    0 => array('a', 'b'),
    1 => array('c', 'd'),
    2 => array('e', 'f'),
    3 => array('g', 'h'),
    4 => array('i', 'j'),
    5 => array('k', 'l'),
    6 => array('m', 'n'),
    7 => array('o', 'p'),
    8 => array('q', 'r')
)

How would I go about doing this? Thanks.

我该怎么做呢?谢谢。

回答by Baba

This simple function would work for you:

这个简单的功能对你有用:

Usage

用法

$array = range("a", "r"); // same as your array
print_r(alternate_chunck($array,12));

Output

输出

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
            [1] => f
        )

    [3] => Array
        (
            [0] => g
            [1] => h
        )

    [4] => Array
        (
            [0] => i
            [1] => j
        )

    [5] => Array
        (
            [0] => k
            [1] => l
        )

    [6] => Array
        (
            [0] => m
        )

    [7] => Array
        (
            [0] => n
        )

    [8] => Array
        (
            [0] => o
        )

    [9] => Array
        (
            [0] => p
        )

    [10] => Array
        (
            [0] => q
        )

    [11] => Array
        (
            [0] => r
        )

)

UpdateThe above might not be useful for most cases ... here is another type of chunk

更新以上在大多数情况下可能没有用......这是另一种类型的块

$array = range("a", "r"); // same as your array
print_r(fill_chunck($array, 5));

Output

输出

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
            [2] => c
            [3] => d
        )

    [1] => Array
        (
            [0] => e
            [1] => f
            [2] => g
            [3] => h
        )

    [2] => Array
        (
            [0] => i
            [1] => j
            [2] => k
            [3] => l
        )

    [3] => Array
        (
            [0] => m
            [1] => n
            [2] => o
            [3] => p
        )

    [4] => Array
        (
            [0] => q
            [1] => r
        )

)

This would make sure the group at no time is more that 5 elements where the other one has no limitation

这将确保该组在任何时候都不会超过 5 个元素,而另一个元素没有限制

Function Used

使用的功能

function alternate_chunck($array, $parts) {
    $t = 0;
    $result = array();
    $max = ceil(count($array) / $parts);
    foreach(array_chunk($array, $max) as $v) {
        if ($t < $parts) {
            $result[] = $v;
        } else {
            foreach($v as $d) {
                $result[] = array($d);
            }
        }
        $t += count($v);
    }
    return $result;
}


function fill_chunck($array, $parts) {
    $t = 0;
    $result = array_fill(0, $parts - 1, array());
    $max = ceil(count($array) / $parts);
    foreach($array as $v) {
        count($result[$t]) >= $max and $t ++;
        $result[$t][] = $v;
    }
    return $result;
}

回答by iiro

You said:

你说:

I have 13 categories in the DB that I want to group them into 12 arrays. If there are more than 12 categories, which there are, then insert the remaining values starting from the first array.

我在数据库中有 13 个类别,我想将它们分成 12 个数组。如果有超过 12 个类别,则从第一个数组开始插入剩余的值。

This works, but what should be the output if you have more elements in the input array?

这是有效的,但是如果输入数组中有更多元素,输出应该是什么?

$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm');

function s($array, $am) {
    $r = array();
    $d = count($array) - $am+1;
    foreach ($array as $k => $v) {
        if ($k < $d) {
            if (!isset($r[0])) {
                $r[0] = array($v);
            } else {
                $r[0] = array_merge($r[0], array($v));
            }
        } else {
            $r[] = array($v);
        }
    }

    return $r;
}

will return

将返回

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
        )

    [2] => Array
        (
            [0] => d
        )

    [3] => Array
        (
            [0] => e
        )

    [4] => Array
        (
            [0] => f
        )

    [5] => Array
        (
            [0] => g
        )

    [6] => Array
        (
            [0] => h
        )

    [7] => Array
        (
            [0] => i
        )

    [8] => Array
        (
            [0] => j
        )

    [9] => Array
        (
            [0] => k
        )

    [10] => Array
        (
            [0] => l
        )

    [11] => Array
        (
            [0] => m
        )

)

回答by mickmackusa

Allow me to be the first to offer a math-based, loopless solution.

让我成为第一个提供基于数学的无环解决方案的人。

The magic in the math is determining which portion of elements belongs in the first set of chunks where all columns are filled in each row versus which elements belong in the second set (if the set should even exist) where all columns except the right-most column are filled.

数学中的魔法是确定元素的哪一部分属于第一组块,其中所有列都填充在每一行中,哪些元素属于第二组(如果该组应该存在),其中除最右边的所有列列被填满。

Let me draw what I'm talking about. The >marks the division between the two chunked arrays.

让我画出我正在谈论的内容。该>标记在两个分块阵列之间的划分。

$size = 9;        -------------    $size = 9;        -------------
$maxrows = 4;   1 | A , B , C |    $maxrow = 3;      | A , B , C |
$columns = 3;   > |-----------|    $columns = 3;   1 | D , E , F |
$fullrows = 1;    | D , E |        $fullrows = 3;    | G , H , I |
                2 | F , G |                        > -------------
                  | H , I |                        2      n/a
                  ---------


$size = 18;        ---------    $size = 17;       -------------------------------------
$maxrows = 12;     | A , B |    $maxrows = 2;   1 | A , B , C , D , E , F , G , H , I |
$columns = 2;      | C , D |    $columns = 9;   > -------------------------------------
$fullrows = 6;     | E , F |    $fullrows = 1;  2 | J , K , L , M , N , O , P , Q |
                 1 | G , H |                      ---------------------------------
                   | I , J |
                   | K , L |
                 > ---------
                   | M |
                   | N |
                   | O |
                 2 | P |
                   | Q |
                   | R |
                   -----

Code: (Demo)

代码:(演示

function double_chunk($array, $maxrows) {
    $size = sizeof($array);
    $columns = ceil($size / $maxrows);
    $fullrows = $size - ($columns - 1) * $maxrows;

    if ($fullrows == $maxrows) {
        return array_chunk($array, $fullrows);  // all columns have full rows, don't splice
    }
    return array_merge(
               array_chunk(
                   array_splice($array, 0, $columns * $fullrows),  // extract first set to chunk
                   $columns
               ),
               array_chunk($array, $columns - 1)   // chunk the leftovers
           );
}
var_export(double_chunk(range('a', 'i'), 3));


If you don't mind the iterated array_splice()calls, this is more brief and perhaps easier to follow (...perhaps not):

如果您不介意重复array_splice()调用,这会更简短,可能更容易理解(...也许不是):

Code: (Demo)

代码:(演示

function custom_chunk($array, $maxrows) {
    $size = sizeof($array);
    $columns = ceil($size / $maxrows);
    $fullrows = $size - ($columns - 1) * $maxrows;

    for ($i = 0; $i < $maxrows; ++$i) {
        $result[] = array_splice($array, 0, ($i < $fullrows ? $columns : $columns - 1));
    }
    return $result;
}
var_export(custom_chunk(range('a', 'r'), 12));

回答by Vijaya Pandey

You can use array_chunkand array_mergefor this problem:

您可以使用array_chunkandarray_merge解决这个问题:

<?php 

$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r');
$chunked_arr = array_chunk($array,12);
$j = 0;
for($i = 0; $i < count($chunked_arr[0]); $i++){
    if(!($i % 2 == 0)){
        $first_combined[$j][$i % 2] = $chunked_arr[0][$i];
        $j++;
    } else {
    $first_combined[$j][$i % 2] = $chunked_arr[0][$i];
    }
}

$merged_array = array_merge($first_combined, $chunked_arr[1]); 

echo '<pre>';
print_r($merged_array);
 ?>

And You will get the result like this:

你会得到这样的结果:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
            [1] => f
        )

    [3] => Array
        (
            [0] => g
            [1] => h
        )

    [4] => Array
        (
            [0] => i
            [1] => j
        )

    [5] => Array
        (
            [0] => k
            [1] => l
        )

    [6] => m
    [7] => n
    [8] => o
    [9] => p
    [10] => q
    [11] => r
)

This is what exactly you want.

这正是您想要的。

Live Demo Here>>

现场演示在这里>>

回答by Ankit Gupta

<?php
$array = range('a','r');
$length = array(2=>6,1=>6); // 2=>6 means -- first six elements of new array will have 2 elements each and then, 1=>6 means -- next six elements of new array will have 1 element each
$target = array(); // or use []  in PHP 5.4
foreach($length as $i=>$times) {
    while($times>0){
        $target[] = array_splice($array, 0, $i);
        $times--;
    }
}
print_r($target);
?>

回答by Nikitas

Compile that and see if it does for you:

编译它,看看它是否适合你:

<?php

$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm');

$sliceA = 0;
$sliceB = 2;

$final = array(array_slice($array, $sliceA, $sliceB));


for ($i=$sliceB; $i<sizeof($array); $i++)
{
    $final[$sliceB-1] = array($array[$i]);
    $sliceB++;
}

var_dump($final);

回答by bizzehdee

ceil(count($array) / $parts)would give 2, so each array is being filled up with 2 items until you dont have 2 items left. hence the last one has 1 item. this will work when you have a huge amount of data in the array, but not so much when you have a small amount of data.

ceil(count($array) / $parts)会给出 2,所以每个数组都被填满了 2 个项目,直到你没有剩下 2 个项目为止。因此最后一个有 1 个项目。当数组中有大量数据时,这会起作用,但当数据量很少时,这会起作用。

回答by Simon Groenewolt

What you are describing is not what array_chunk is made for. You should use array_slice()and calculate yourself which parts of the array you want to end up as new arrays. (and use a for loop to iterate over your original array)

您所描述的不是 array_chunk 的用途。您应该使用array_slice()并计算自己想要将数组的哪些部分作为新数组结束。(并使用 for 循环遍历原始数组)

Update:

更新:

Some calculations that could help you:

一些可以帮助您的计算:

minimum_fill = floor(array_length / nr_buckets)
bigger_buckets_amount = array_length - (minimum_fill / nr_buckets)

Algorithm to fill buckets: Loop over the array, fill the first bigger_buckets_amountamount of buckets with (minimum_fill + 1), fill the rest of the buckets with minimum_fill

填充桶的算法:循环遍历数组,用 填充第一个bigger_buckets_amount桶,用(minimum_fill + 1)填充其余的桶minimum_fill

回答by CodeWalker

This will do it for you!
Here, I used my function smallify() to break an array of 15 elements into 3 arrays of 5 elements each.

这将为您做到!
在这里,我使用我的函数 smallify() 将一个包含 15 个元素的数组分成 3 个每个包含 5 个元素的数组。

<?php

$bigArray = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);

echo ("<pre>");
print_r (smallify($bigArray, 3));
echo ("<pre/>");


function smallify($arr, $numberOfSlices){

  $sliceLength = sizeof($arr) /$numberOfSlices;
  for($i=1; $i<=$numberOfSlices; $i++){

       $arr1 = array_chunk($arr, $sliceLength*$i);
       return $arr1;
       unset($arr1);

   }

}
?>

Result

结果

Array
(
[0] => Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
        [3] => 4
        [4] => 5
    )

[1] => Array
    (
        [0] => 6
        [1] => 7
        [2] => 8
        [3] => 9
        [4] => 10
    )

[2] => Array
    (
        [0] => 11
        [1] => 12
        [2] => 13
        [3] => 14
        [4] => 15
    )

)

回答by Eren

Can you try using the following simple function?

您可以尝试使用以下简单功能吗?

$cols = array2cols($array,12);

$cols = array2cols($array,12);

function array2cols($array,$n){
    $groups = array();
    for($i=0;$i<$n;$i++){
        $groups[$i] = array();
    }
    $col = 0;
    foreach($array as $row){
        $groups[$col][] = $row;
        $col = ($col+1)%$n;
    }
    return $groups;
}