PHP函数在N个子数组中分配N个元素的数组 [英] PHP Function to devide an array of N elements in N sub array
本文介绍了PHP函数在N个子数组中分配N个元素的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有N个元素的数组。我想将其尽可能平均地划分为M个子数组,以形成M列。
Let say I have an array of N elements. I want to divide it as much as possible equally into M sub arrays to make M columns.
您知道如何在PHP中做到这一点吗?
我已经尝试过 array_chunk ,但这不是很
Do you know how I could do that in PHP ? I've tried array_chunk, but it's not quite what I'm looking for.
这是两个示例:
$array = range(1, 10);
$number_of_split = 3;
该数组应分为3个子数组,其中第一个子数组为4个元素,其他两个子数组为3个元素
The array should be split into 3 sub arrays of 4 elements for the first sub array and 3 elements for the two other sub arrays.
$array = range(1, 27);
$number_of_split = 5;
应将数组分为5个子数组,其中第一个两个子数组的元素为6个,其他三个数组的子元素为5个子数组。
The array should be split into 5 sub arrays of 6 elements for the two first sub arrays and 5 elements for the three other sub arrays.
推荐答案
请尝试从 php.net 。
function partition($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;
}
像这样使用:
$array = array();
$array = range(1, 10);
$number_of_split = 3;
$chunks = partition($array, $number_of_split);
print_r($chunks);
这篇关于PHP函数在N个子数组中分配N个元素的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文