在PHP中使用迭代器實(shí)現(xiàn)分頁(yè)功能可以通過(guò)以下步驟來(lái)實(shí)現(xiàn):
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); // 假設(shè)有100條數(shù)據(jù)
$paginator = new Paginator($data);
foreach ($paginator as $page) {
foreach ($page as $item) {
echo $item . ' ';
}
echo '<br>';
}
以上代碼將會(huì)將數(shù)據(jù)按照每頁(yè)10條的方式進(jìn)行分頁(yè)展示,每次循環(huán)輸出一個(gè)頁(yè)面的數(shù)據(jù)。