[英]php array_chunk with balanced number of elements
我需要將一個數組拆分成幾個塊,每個塊都有相同數量的元素(甚至在不同的塊中重復)在輸出之間平衡
所以,例如,從這樣一個數組開始:
$input = array(1,2,3,4,5,6,7,8,9,10,11);
我正在嘗試開發一個接受輸入數組的函數以及每個塊上預期的元素數。 所以例如[ balanced_chunk($ input,3) ]
應該得到我
0 => array(1,2,3)
1 => array(4,5,6)
2 => array(6,7,8) #-- Value 6 is repeated
3 => array(9,10,11)
只要[ balanced_chunk($ input,5) ]
應該得到我
0 => array(1,2,3,4,5)
1 => array(4,5,6,7,8) #-- Value 4,5 are repeated
2 => array(7,8,9,10,11) #-- Value 7,8 are repeated
等等
首先,我開發了這樣的功能
function balanced_chunk($input, $size) {
$step = ceil(count($input) / $size);
$chunks = range(0, count($input), count($input) / $step);
reset($chunks);
while (list(,$start) = each($chunks)) {
$start = (fmod($start, 1) <= 0.5 ? floor($start) : ceil($start));
$clist[] = array_slice($input, $start, $size, true);
}
return($clist);
}
但由於我錯過的那一刻,它得到了我這樣的輸出:
[0] => Array (1,2,3,4,5)
[1] => Array (5,6,7,8,9) #-- this element should instead start from 4...
[2] => Array (8,9,10,11) #-- last element contains only 4 value
只是為了做一個更好的例子考慮輸入數組[a,b,c,d,e,f,g,h,i,l,m,n,o,p]
一個平衡的塊,每個必須有5個元素
[ a,b,c,d,e ]
[ f,g,h,i,l ]
[ l,m,n,o,p ] #-- letter 'l' is repeated twice on 3rd result
或(作為有效的替代方案)
[ a,b,c,d,e ]
[ e,f,g,h,i ] #-- letter 'e' is repeated twice on 2nd result
[ l,m,n,o,p ]
一個平衡的塊,每個必須有8個元素
[ a,b,c,d,e,f,g,h ]
[ g,h,i,l,m,n,o,p ] #-- letter 'g','h' are repeated twice
我被困了! 經過myselft的幾次試驗后,我無法找到如何解決這個問題。
你現在可能已經轉向了其他事情! 但這是我這樣做的方式。
function balanced_chunk($input, $size)
{
$len = count($input);
$chunkSize = ceil($len / $size);
$o = [];
$i = 1;
$k = 0;
foreach ($input as $elem)
{
$o[$k][$i] = $elem;
$k = ($i % $chunkSize == 0) ? $k+1 : $k;
$i++;
}
return $o;
}
目前,等待找到“更聰明”的方法,我找到了這個解決方案:
function balanced_chunk($input, $size) {
$chunks = ceil(count($input) / $size);
$step = count($input) / $chunks;
$chunklist = array();
for ($i = 0; $i < count($input); $i += $step) {
$chunk = array_slice($input, floor($i), $size);
if (count($chunk) < $size) $chunk = array_slice($input, $size * -1, $size, true);
$chunklist[] = $chunk;
}
return($chunklist);
}
這意味着,例如...... Ex#1:11個元素分為3個塊:
$split = balanced_chunk(range(1, 11), 3));
/*
[ 1,2,3 ]
[ 3,4,5 ][ 6,7,8 ][ 9,10,11 ]
In such case the fx needs to be better tuned as a better balanced output
has instead to be
[ 1,2,3 ][ 4,5,6 ]
[ 6,7,8 ][ 9,10,11 ]
*/
例2:11個元素分為4個塊:
$split = balanced_chunk(range(1, 11), 4));
/*
[ 1,2,3,4 ]
[ 4,5,6,7 ][ 8,9,10,11 ]
In such case the given output is exactly comparable with the alternative
[ 1,2,3,4 ][ 5,6,7,8 ]
[ 8,9,10,11 ]
*/
例#3:11個元素分為5個塊:
$split = balanced_chunk(range(1, 11), 5));
/*
[ 1,2,3,4,5 ]
[ 4,5,6,7,8 ]
[ 7,8,9,10,11 ]
*/
例#4:11個元素分為7個塊:
$split = balanced_chunk(range(1, 11), 7));
/*
[ 1,2,3,4,5,6,7 ]
[ 5,6,7,8,9,10,11 ]
*/
我歡迎提出改進建議或建議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.