【问题标题】:php calculation solution for pagination分页的php计算解决方案
【发布时间】:2012-12-21 02:55:34
【问题描述】:

我有一个变量$total 是结果总数,$page 是页码。结果限制为每页 12 个。

假设如果$total 为24,则脚本可能会分别为$page=1 和$page=2 返回1 和2。如果输入数字小于 1(负数或零)或数字大于 2,它也应该返回 1

再次假设如果$total 为25,则脚本可能分别为$page=1、$page=2 和$page=3 返回1、2 和3。如果输入数字小于 1(负数或零)或数字大于 1,它也应该返回 1

【问题讨论】:

标签: php


【解决方案1】:

这是一种计算方法:

// Assuming you have the $total variable which contains the total
//   number of records

$recordsPerPage = 12;

// Declare a variable which will hold the number of pages required to
//   display all the records, when displaying @recordsPerPage records on each page    
$maxPages = 1;

if($total > 0)
   $maxPages = (($total - 1) / $recordsPerPage) + 1;

// $maxPages now contains the number of pages required. you can do whatever 
//   it is you need to do with it. It wasn't clear from the question..

return $maxPages;

此外,如果您想生成一个包含每个可用页面的索引的数组,您可以这样做:

$pages = array();
for($i = 1; $i <= $maxPages; i++)
{
    array_push($pages, $i);
}

print_r($pages);

【讨论】:

  • 我认为只需要做 floor($maxPages)。
猜你喜欢
  • 2012-01-04
  • 1970-01-01
  • 1970-01-01
  • 2016-10-29
  • 1970-01-01
  • 1970-01-01
  • 2012-12-30
  • 2021-02-16
  • 2017-08-27
相关资源
最近更新 更多