如何使用开始索引、每页项目数、总项目数和总页数获取当前页面?(菲律宾比索)


How to get current page using start index, items per page, total items, and total pages? (PHP)

例如,假设:

$startIndex = 21; 
$totalItems = 100;
$itemsPerPage = 10;
$totalPages = ceil($totalItems / $itemsPerPage);  // (10)
$currentpage = //I am stumped here.

基于$startIndex,$currentpage会是什么?

我正在研究分页,它踢我的屁股。我知道这可能是一些非常简单的数学,但我现在无法思考。

每页有 10 个项目,假设您的项目计数/编号从 1 开始,则第 1 页包含项目 1 到 10,第 2 页包含项目 11 到 20,第 3 页包含 21 到 30,依此类推。

所以

$currentPage = ceil(($startIndex - 1) / $itemsPerPage) + 1;

我使用ceil()来确保您有一个整数,该整数向上舍入,因此当前页码正确。


如果您的项目计数从 0 开始,因此第 1 页包含项目 0 到 9,则可以跳过公式的- 1+ 1部分:

$currentPage = ceil(($startIndex) / $itemsPerPage);

你在数学课上睡了很多,不是吗?

$currentpage = (($startIndex - 1) / $itemsPerPage) + 1;

如果:

$startIndex = 21; 
$totalItems = 100;
$itemsPerPage = 10;
$totalPages = ($totalItems / $itemsPerPage);  // (10)

然后

$currentpage = $startIndex/$itemsPerPage; //Make sure that it uses integer division

使用 floor 获取当前页面很重要

pagesTotal = int(ceil(count / limit))
pagesCurrent = int(floor(offset / limit) + 1)