PHP搜索分页类
在PHP中,我们可以创建一个名为Pagination
的类来实现搜索结果的分页功能,以下是一个简单的示例:
(图片来源网络,侵删)
class Pagination { private $totalItems; private $itemsPerPage; private $currentPage; private $totalPages; public function __construct($totalItems, $itemsPerPage, $currentPage) { $this->totalItems = $totalItems; $this->itemsPerPage = $itemsPerPage; $this->currentPage = $currentPage; $this->totalPages = ceil($this->totalItems / $this->itemsPerPage); } public function getStartIndex() { return ($this->currentPage 1) * $this->itemsPerPage; } public function getEndIndex() { return min($this->getStartIndex() + $this->itemsPerPage 1, $this->totalItems 1); } public function hasPreviousPage() { return $this->currentPage > 1; } public function hasNextPage() { return $this->currentPage < $this->totalPages; } public function getPreviousPage() { return $this->hasPreviousPage() ? $this->currentPage 1 : null; } public function getNextPage() { return $this->hasNextPage() ? $this->currentPage + 1 : null; } public function getCurrentPage() { return $this->currentPage; } public function getTotalPages() { return $this->totalPages; } }
使用示例
假设我们有一个包含100个项目的数组,我们希望每页显示10个项目,并当前在第3页,我们可以这样使用Pagination
类:
$totalItems = 100; $itemsPerPage = 10; $currentPage = 3; $pagination = new Pagination($totalItems, $itemsPerPage, $currentPage); echo "当前页: " . $pagination->getCurrentPage() . "<br>"; echo "总页数: " . $pagination->getTotalPages() . "<br>"; echo "起始索引: " . $pagination->getStartIndex() . "<br>"; echo "结束索引: " . $pagination->getEndIndex() . "<br>"; echo "是否有上一页: " . ($pagination->hasPreviousPage() ? "是" : "否") . "<br>"; echo "是否有下一页: " . ($pagination->hasNextPage() ? "是" : "否") . "<br>"; echo "上一页: " . ($pagination->getPreviousPage() ?: "无") . "<br>"; echo "下一页: " . ($pagination->getNextPage() ?: "无") . "<br>";
这将输出以下信息:
当前页: 3 总页数: 10 起始索引: 20 结束索引: 29 是否有上一页: 是 是否有下一页: 是 上一页: 2 下一页: 4
(图片来源网络,侵删)
本文来源于互联网,如若侵权,请联系管理员删除,本文链接:https://www.9969.net/48963.html