在foreach循环中定义偏移量

时间:2012-11-19 05:48:00

标签: php pagination offset

我已经在程序员的一个网站上实现了一个类分页。现在我想将它实现到另一个。区别在于他正在使用限制和偏移并从数据库中获取数据,现在有一个foreach循环,我是php的初学者。 所以有代码:

$page = !empty($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 10;
$total_count = 25; \\ should be dynamic here

$pagination = new Pagination($page, $per_page, $total_count);

foreach(...

)

分页类包含确定是否存在上一页,下一页等的方法,并且这些方法正常工作。只是我在所有3页中只获得前10名。 提前谢谢!

分页课程看起来像这样

<?php

// This is a helper class to make paginating 
// records easy.
class Pagination {

  public $current_page;
  public $per_page;
  public $total_count;

  public function __construct($page=1, $per_page=10, $total_count=0){
    $this->current_page = (int)$page;
    $this->per_page = (int)$per_page;
    $this->total_count = (int)$total_count;
  }

  public function offset() {
    // Assuming 20 items per page:
    // page 1 has an offset of 0    (1-1) * 20
    // page 2 has an offset of 20   (2-1) * 20
    //   in other words, page 2 starts with item 21
    return ($this->current_page - 1) * $this->per_page;
  }

  public function total_pages() {
    return ceil($this->total_count/$this->per_page);
    }

  public function previous_page() {
    return $this->current_page - 1;
  }

  public function next_page() {
    return $this->current_page + 1;
  }

    public function has_previous_page() {
        return $this->previous_page() >= 1 ? true : false;
    }

    public function has_next_page() {
        return $this->next_page() <= $this->total_pages() ? true : false;
    }


}

?>

0 个答案:

没有答案