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

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

问题描述

我知道 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 个块各有 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天全站免登陆