分裂数组chuncks特定数量的 [英] Split array into a specific number of chuncks
问题描述
我知道array_chunck允许分割的阵列成几个chuncks,但根据元素的数量的的chuncks变化次数。我需要的是对阵列总是分裂成像4阵列例如阵列的特定号码。
I know that array_chunck allows to split an array into several chuncks, but the number of chuncks 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.
以下code分割数组3 chuncks,二chuncks每2个元素和1 chunch 1元。我想是到阵列总是分成4 chuncks,不管总的元素数量的阵列,但总是试图在chuncks均匀划分的元素如array_chunck功能一样。我怎样才能做到这一点?是否有任何PHP函数呢?
The following code splits the array into 3 chuncks, two chuncks with 2 elements each and 1 chunch with 1 element. What I would like is to split the array always into 4 chuncks, no matter the number of total elements that the array has, but always trying to divide the elements evenly in the chuncks 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;
}
这篇关于分裂数组chuncks特定数量的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!