涉及到分页时, 除非只显示上一页/下一页, 否则需要计算起始页和结束页. 看过很多代码都是用大量的if-else来实现, 代码量大, 又不简洁. 现在提供一种只需要3行代码的算法.
一个好的分页算法, 应该具有下面的优点:
当前页码应该尽量在正中间.
如果”首页”和”尾页”不可用(当前处于第一页或最后一页), 不要隐藏这两组文字, 以免链接按钮位置变动.
算法简单.
下面的算法具有前面1和3两个优点.
代码如下:
// $curr_index, 当前页码.
// $link_count, 链接数量.
// $page_count, 当前的数据的总页数.
// $start, 显示时的起始页码.
// $end, 显示时的终止页码.
$start = max(1, $curr_index – intval($link_count/2));
$end = min($start + $link_count – 1, $page_count);
$start = max(1, $end – $link_count + 1);
start = Math.max(1, curr_index – parseInt(link_count/2));
end = Math.min(page_count, sta来源gaodai$ma#com搞$$代**码网rt + link_count – 1);
start = Math.max(1, end – link_count + 1);
// $link_count, 链接数量.
// $page_count, 当前的数据的总页数.
// $start, 显示时的起始页码.
// $end, 显示时的终止页码.
$start = max(1, $curr_index – intval($link_count/2));
$end = min($start + $link_count – 1, $page_count);
$start = max(1, $end – $link_count + 1);
start = Math.max(1, curr_index – parseInt(link_count/2));
end = Math.min(page_count, sta来源gaodai$ma#com搞$$代**码网rt + link_count – 1);
start = Math.max(1, end – link_count + 1);
以上就是php 3行代码的分页算法(求起始页和结束页)的详细内容,更多请关注gaodaima搞代码网其它相关文章!