【问题标题】:Calculating offset for a for loop计算for循环的偏移量
【发布时间】:2011-06-20 16:58:48
【问题描述】:

我正在尝试对我得到的数组进行分页,目前我正在使用这样的 for 循环遍历它

for($i = $pages->low;$i<$total;++$i)

我需要弄清楚的是如何根据当前页面和行数计算出$total 变量,以便循环正确处理数组中的项目数量。

我有以下变量:


    $pages->low (equals the number of rows the pagination has already been through
    e.g. Page 1 = 0, Page 2 = 5, Page 3 = 10 etc...

    $pages->total_items (explains itself)
    $pages->current_page
    $pages->ipp (items per page, FYI 5)

那么我将使用什么公式来计算循环应该经过的行数,例如,如果数组中总共有 13 个项目并且每页有 5 个结果,则在第一页 $total 应该等于 5,页两个应该等于 10,第三页应该等于 13 等等?

谢谢

【问题讨论】:

  • 那是小学数学。你确定你可以在没有基本算术的情况下编程吗?

标签: php loops pagination for-loop offset


【解决方案1】:
$total = min($pages->ipp * ($pages->current_page + 1), $pages->total_items);

它是显而易见的,但它限制了项目的总数。

虽然我个人只是在这里使用LimitIterator

【讨论】:

  • 这很完美(LimitIterator),比我之前使用的延迟 for 循环要好得多。
【解决方案2】:
$start_from = ($current_page - 1) * $per_page;

来自 Kohana 的分页模块:

$this->total_pages        = (int) ceil($this->total_items / $this->items_per_page);
$this->current_page       = (int) min(max(1, $this->current_page), max(1, $this->total_pages));
$this->current_first_item = (int) min((($this->current_page - 1) * $this->items_per_page) + 1, $this->total_items);
$this->current_last_item  = (int) min($this->current_first_item + $this->items_per_page - 1, $this->total_items);
$this->previous_page      = ($this->current_page > 1) ? $this->current_page - 1 : FALSE;
$this->next_page          = ($this->current_page < $this->total_pages) ? $this->current_page + 1 : FALSE;
$this->first_page         = ($this->current_page === 1) ? FALSE : 1;
$this->last_page          = ($this->current_page >= $this->total_pages) ? FALSE : $this->total_pages;
$this->offset             = (int) (($this->current_page - 1) * $this->items_per_page);

【讨论】:

    【解决方案3】:

    不清楚,为什么如果第一页有 13 个项目,总数应该等于 5 ???

    如果你想在第 2 页上显示 $pages->ipp 下一个项目,我只需要从 $pages->low$pages ->low + $pages->ipp

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      • 1970-01-01
      • 2013-08-24
      相关资源
      最近更新 更多