陣列分頁是處理記憶體內資料集(如 API 回傳、快取資料、小型查詢結果)的常見需求。本文實作一個可重複使用的 ArrayPaginator 類別,支援當前頁、每頁筆數、總頁數計算、資料切片、分頁導航連結產生。
<?php
class ArrayPaginator
{
/** @var array 原始資料陣列 */
private array $data;
/** @var int 每頁筆數 */
private int $perPage;
/** @var int 當前頁碼 (1-based) */
private int $currentPage;
/** @var string 額外查詢參數(如排序、篩選) */
private string $queryParams = '';
public function __construct(array $data = [], int $perPage = 10, int $currentPage = 1)
{
$this->data = $data;
$this->perPage = max(1, $perPage);
$this->currentPage = max(1, $currentPage);
}
/** 以關聯陣列批次設定 */
public function setArguments(array $args): void
{
$this->data = $args['data'] ?? $this->data;
$this->perPage = $args['perPage'] ?? $this->perPage;
$this->currentPage = $args['currentPage'] ?? $this->currentPage;
}
/** 設定額外查詢參數字串(如 "sort=name&dir=asc") */
public function setQueryParams(string $params): void
{
$this->queryParams = $params;
}
/** 執行分頁,回傳 [ 'items' => [...], 'pagination' => [...] ] */
public function paginate(): array
{
$totalItems = count($this->data);
$totalPages = (int)ceil($totalItems / $this->perPage);
$currentPage = min($this->currentPage, max(1, $totalPages));
$offset = ($currentPage - 1) * $this->perPage;
$items = array_slice($this->data, $offset, $this->perPage);
return [
'items' => $items,
'pagination' => [
'totalItems' => $totalItems,
'totalPages' => $totalPages,
'currentPage' => $currentPage,
'perPage' => $this->perPage,
'hasPrev' => $currentPage > 1,
'hasNext' => $currentPage < $totalPages,
'prevPage' => max(1, $currentPage - 1),
'nextPage' => min($totalPages, $currentPage + 1),
'firstPage' => 1,
'lastPage' => max(1, $totalPages),
'links' => $this->buildLinks($currentPage, $totalPages),
],
];
}
/** 產生分頁導航 HTML 連結 */
private function buildLinks(int $current, int $total): array
{
$baseUrl = $_SERVER['REQUEST_URI'];
// 移除現有 page 參數
$parsed = parse_url($baseUrl);
$query = $parsed['query'] ?? '';
parse_str($query, $params);
unset($params['page']);
$build = function (int $page, string $label) use ($params) {
$params['page'] = $page;
$queryStr = http_build_query($params);
$url = ($parsed['path'] ?? '') . ($queryStr ? '?' . $queryStr : '');
return ['url' => $url, 'label' => $label, 'page' => $page, 'active' => $page === $current];
};
$links = [];
$links[] = $build(1, '首頁');
$links[] = $build(max(1, $current - 1), '上一頁');
// 數字頁碼(顯示當前頁前後各 2 頁)
$start = max(1, $current - 2);
$end = min($total, $current + 2);
for ($i = $start; $i <= $end; $i++) {
$links[] = $build($i, (string)$i);
}
$links[] = $build(min($total, $current + 1), '下一頁');
$links[] = $build($total, '尾頁');
return $links;
}
}
<?php
require_once 'ArrayPaginator.php';
// 模擬資料
$data = range(1, 105); // 105 筆資料
// 從 GET 取得頁碼
$page = max(1, (int)($_GET['page'] ?? 1));
// 實例化
$paginator = new ArrayPaginator($data, 10, $page);
// 保留其他查詢參數
$paginator->setQueryParams(http_build_query(array_diff_key($_GET, ['page' => ''])));
// 執行分頁
$result = $paginator->paginate();
// 輸出資料
foreach ($result['items'] as $item) {
echo "項目 $item";
}
// 輸出分頁導航
$pg = $result['pagination'];
echo '';
// 顯示資訊
echo "第 {$pg['currentPage']} / {$pg['totalPages']} 頁,共 {$pg['totalItems']} 筆
";
// array_slice 預設重新索引,若需保留鍵名:
$items = array_slice($this->data, $offset, $this->perPage, true); // 第 4 參數 true
<?php
// 使用 Laravel 的 LengthAwarePaginator(需 illuminate/pagination 套件)
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
$collection = new Collection($data);
$paginator = new LengthAwarePaginator(
$collection->forPage($page, $perPage),
$collection->count(),
$perPage,
$page,
['path' => request()->url(), 'query' => request()->query()]
);
return view('list', ['paginator' => $paginator]);
| 資料量 | 建議做法 |
|---|---|
| < 10,000 筆 | 記憶體陣列分頁(本類別) |
| 10,000 ~ 100,000 | 資料庫 LIMIT/OFFSET 分頁 |
| > 100,000 | 游標分頁 / ID 偏移分頁 / Elasticsearch |
ArrayPaginator 封裝了分頁核心邏輯:總數計算、切片、導航連結產生。實務上可依專案需求擴充:加入 setItemTransformer(callable $fn) 格式化項目、支援 JSON API 回傳標準格式、整合 Bootstrap/Tailwind CSS 樣式。記住:**大量資料務必在資料庫層分頁**,陣列分頁僅適用於已載入記憶體的小型資料集。