在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条的方式进行分页展示,每次循环输出一个页面的数据。