将数组拆分为特定数量的块 [英] Split array into a specific number of chunks

查看:96
本文介绍了将数组拆分为特定数量的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道array_chunk()允许将数组分成几个块,但是块的数量根据元素的数量而变化.我需要的是始终将数组拆分为特定数量的数组,例如4个数组.

I know that array_chunk() allows to split an array into several chunks, but the number of chunks changes according to the number of elements. What I need is to always split the array into a specific number of arrays like 4 arrays for example.

以下代码将数组分成3个块,两个块各2个元素,一个块1个元素.我想要的是将数组始终拆分为4个块,而不管该数组具有的元素总数如何,但总是像array_chunck函数一样尝试将元素均匀地划分为块.我该怎么做?是否有任何PHP函数?

The following code splits the array into 3 chunks, two chunks with 2 elements each and 1 chunk with 1 element. What I would like is to split the array always into 4 chunks, no matter the number of total elements that the array has, but always trying to divide the elements evenly in the chunks like the array_chunck function does. How can I accomplish this? Is there any PHP function for this?

$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));

谢谢.

推荐答案

您可以尝试

$input_array = array(
        'a',
        'b',
        'c',
        'd',
        'e'
);

print_r(partition($input_array, 4));

输出

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

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

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

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

)

使用的功能

/**
 * 
 * @param Array $list
 * @param int $p
 * @return multitype:multitype:
 * @link http://www.php.net/manual/en/function.array-chunk.php#75022
 */
function partition(Array $list, $p) {
    $listlen = count($list);
    $partlen = floor($listlen / $p);
    $partrem = $listlen % $p;
    $partition = array();
    $mark = 0;
    for($px = 0; $px < $p; $px ++) {
        $incr = ($px < $partrem) ? $partlen + 1 : $partlen;
        $partition[$px] = array_slice($list, $mark, $incr);
        $mark += $incr;
    }
    return $partition;
}

这篇关于将数组拆分为特定数量的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆