我有一些项目组(例如计数[3,2,0,4,1,0,1,1,1,0,5,2,3]),我希望每个项目的最小数量页面(最后一页除外)。 array_slice当前使用counts数组作为输入,但最终它将使用相应的数据作为输入。最终版本只能使用array_slice一次 - 用于当前查看的页面。我在想,如果代码可以使用特殊的PHP函数进行更优雅e.g等PHP将页面更优雅地分成页面?
输出:每页
项目:1 NUM页:10
3; 2; 0,4; 1; 0,1; 1; 1; 0,5; 2; 3;
每页项目数:2个编号页数:8
3; 2; 0,4; 1,0,1; 1,1; 0,5; 2; 3;
每页项目数:3个编号页数:5
3; 2,0,4; 1,0,1,1; 1,0,5; 2,3;
每页项目数:4个编号页数:5
3,2; 0,4; 1,0,1,1,1; 0,5; 2,3;
每页项目数:5个数页数:4
3,2; 0,4,1; 0,1,1,1,0,5; 2,3;
每页项目数:6个编号页数:3
3,2,0,4; 1,0,1,1,1,0,5; 2,3;
<?php
$group_counts = [3,2,0,4,1,0,1,1,1,0,5,2,3];
splitOntoPages($group_counts, 1);
splitOntoPages($group_counts, 2);
splitOntoPages($group_counts, 3);
splitOntoPages($group_counts, 4);
splitOntoPages($group_counts, 5);
splitOntoPages($group_counts, 6);
function splitOntoPages($item_group_counts, $items_per_page) {
$page_cumul_totals = [0 => 0];
$page_first_index = [0 => 0];
$page = 0;
foreach ($item_group_counts as $group_index => $group_total) {
$page_cumul_totals[$page] += $group_total;
if ($page_cumul_totals[$page] >= $items_per_page) {
$page++;
$page_first_index[$page] = $group_index + 1;
$page_cumul_totals[$page] = 0;
}
}
$page_first_index[$page + 1] = $group_index + 1;
$numPages = count($page_cumul_totals);
if ($page_cumul_totals[$numPages - 1] == 0) {
$numPages--;
}
echo 'Items per page: '.$items_per_page.' num pages: '.$numPages.'<br>';
for ($p = 0; $p < $numPages; $p++) {
$fromIndex = $page_first_index[$p];
$countOnPage = $page_first_index[$p + 1] - $fromIndex;
$page_items = array_slice($item_group_counts, $fromIndex, $countOnPage);
echo implode(',', $page_items).'; ';
}
echo '<br><br>';
}
我的目标是确定基于给定页码...为array_slice正确的参数,并确定页数。
$ page_items = array_slice($ item_groups,$ fromIndex,$ countOnPage);
你代码运行良好,你只是在寻找可以做得更好的东西,或者你实际上在代码中遇到任何问题? – Xatenev
除了回声之外,我看起来很好。我使用'splitOntoPages'中的单个循环来返回页面的二维矩阵,并在函数外部的另一个循环中打印它们以将分页逻辑与表示分离。 –
Xatenev:最近我一直在使用像array_map,array_walk等,我认为这使得代码更优雅,所以我想知道是否还有其他东西我可以用在这里... –