php 数组实现分页
PHP 数组分页实现方法
在 PHP 中,可以通过数组切片和计算偏移量实现分页功能。以下是两种常见实现方式:
基础数组分页实现
function paginateArray($array, $page, $perPage) {
$totalItems = count($array);
$totalPages = ceil($totalItems / $perPage);
$offset = ($page - 1) * $perPage;
return [
'data' => array_slice($array, $offset, $perPage),
'total' => $totalItems,
'per_page' => $perPage,
'current_page' => $page,
'last_page' => $totalPages
];
}
// 使用示例
$dataArray = range(1, 100); // 示例数组
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 10;
$result = paginateArray($dataArray, $page, $perPage);
带样式分页链接生成
function generatePaginationLinks($currentPage, $totalPages, $url = '?page=') {
$links = '';
$range = 2; // 显示当前页前后页数
for ($i = 1; $i <= $totalPages; $i++) {
if ($i == $currentPage) {
$links .= "<span class='current'>$i</span>";
} elseif ($i >= $currentPage - $range && $i <= $currentPage + $range) {
$links .= "<a href='{$url}{$i}'>$i</a>";
}
}
if ($currentPage > 1) {
$prev = $currentPage - 1;
$links = "<a href='{$url}{$prev}'>« 上一页</a>" . $links;
}
if ($currentPage < $totalPages) {
$next = $currentPage + 1;
$links .= "<a href='{$url}{$next}'>下一页 »</a>";
}
return $links;
}
Laravel 风格分页实现
对于需要更完整分页功能的情况,可以模仿 Laravel 的分页器:
class ArrayPaginator {
protected $items;
protected $perPage;
protected $currentPage;
protected $total;
public function __construct($items, $perPage, $currentPage) {
$this->total = count($items);
$this->items = array_slice($items, ($currentPage - 1) * $perPage, $perPage);
$this->perPage = $perPage;
$this->currentPage = $currentPage;
}
public function links() {
$totalPages = ceil($this->total / $this->perPage);
return generatePaginationLinks($this->currentPage, $totalPages);
}
public function items() {
return $this->items;
}
}
使用注意事项
- 确保页码参数经过验证和类型转换,防止 SQL 注入
- 对于大型数组,考虑性能问题,可能需要改用数据库分页
- 前端显示时可以添加 CSS 样式美化分页控件
这些方法提供了从简单到完整的不同实现方案,可根据项目需求选择适合的方式。







