如何计算分页的偏移量? [英] How do I calculate the offsets for pagination?

查看:1800
本文介绍了如何计算分页的偏移量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写的Web服务中使用分页功能,但是我缺乏数学见识正在使我丧命. 我有几个键:totalItemscurrentItemscurrentPagetotalPages,还有几个指向firstlastpreviousnext的链接.

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 table
  • currentItems: limit parameter from HTTP request
  • currentPage: start parameter divided by limit parameter
  • totalPages: number of rows in the table divided by limit. (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 with limit from the HTTP request
  • last: 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?

我想问的是:我的计算正确吗?以及我该如何解决lastpreviousnext的三个问题?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆