在PHP中使用迭代器實現分頁功能可以通過以下步驟來實現:
class Paginator implements Iterator {
private $data;
private $currentPage;
private $itemsPerPage = 10;
public function __construct($data) {
$this->data = $data;
$this->currentPage = 1;
}
public function rewind() {
$this->currentPage = 1;
}
public function valid() {
return isset($this->data[($this->currentPage - 1) * $this->itemsPerPage]);
}
public function current() {
return array_slice($this->data, ($this->currentPage - 1) * $this->itemsPerPage, $this->itemsPerPage);
}
public function key() {
return $this->currentPage;
}
public function next() {
$this->currentPage++;
}
}
$data = range(1, 100); // 假設有100條數據
$paginator = new Paginator($data);
foreach ($paginator as $page) {
foreach ($page as $item) {
echo $item . ' ';
}
echo '<br>';
}
以上代碼將會將數據按照每頁10條的方式進行分頁展示,每次循環輸出一個頁面的數據。