如何计算分页的偏移量? [英] How do I calculate the offsets for pagination?
问题描述
我正在编写的Web服务中使用分页功能,但是我缺乏数学见识正在使我丧命.
我有几个键:totalItems
,currentItems
,currentPage
,totalPages
,还有几个指向first
,last
,previous
和next
的链接.
I am working on a pagination feature in a web service I am writing, but my lack of math insight is killing me now.
I have a couple of keys: totalItems
, currentItems
, currentPage
, totalPages
, but also a couple of links to first
, last
, previous
and next
.
此刻,我正在进行以下计算:
At this moment, I am doing the following calculations:
-
totalItems
:表中的行数 -
currentItems
:HTTP请求中的limit
参数 -
currentPage
:start
参数除以limit
参数 -
totalPages
:表中的行数除以limit
. (已整理,8.1页= 9页)
totalItems
: number of rows in the tablecurrentItems
:limit
parameter from HTTP requestcurrentPage
:start
parameter divided bylimit
parametertotalPages
: number of rows in the table divided bylimit
. (Rounded up, 8.1 page = 9 pages)
我认为这些计算是正确的,我正在努力解决以下问题:
I assume those calculations to be correct, what I am struggling with is the following:
-
first
:start
参数为1,HTTP请求中的limit
-
last
:应该是最后一页的第一项,如何正确计算? -
previous
:应该是上一页的第一项,我该怎么做? -
next
:应该是下一页的第一项,我该怎么做?
first
:start
parameter is 1 withlimit
from the HTTP requestlast
: should be the first item of the last page, how do I calculate this correctly?previous
: should be the first item of the previous page, how do I do this?next
: should be the first item of the next page, how do I do this?
我想问的是:我的计算正确吗?以及我该如何解决last
,previous
和next
的三个问题?
What I would like to ask, is: are my calculations correct? And how do I tackle the three problems with last
, previous
and next
?
推荐答案
如果使用mysql
LIMIT offset, items_per_page
要计算偏移量,您可以使用
To calculate the offset u can use
$offset = ($page - 1) * $items_per_page;
然后相应地替换$page
.
最后
$last_offset = ($totalPages - 1) * $items_per_page;
上一个
$previous_offset = (($currentPage - 1) - 1) * $items_per_page;
下一个
$next_offset = (($currentPage + 1) - 1) * $items_per_page;
if ($previous_offset > 0) echo '<a href="?start='.$previous_offset.'&limit='.$items_per_page.'>prev</a>';
if ($next_offset <= $totalPages * $items_per_page) echo '<a href="?start='.$next_offset.'&limit='.$items_per_page.'">prev</a>';
这篇关于如何计算分页的偏移量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!