开发者

php calculation solution for pagination

I have a variable $total which is the total number of results and $page which is the page number. The result is limited to 12 per page.

Suppose if $total is 24, the script may return 1 and 2 for $page=1 and $page=2 respectively. It should also return 1 if the input number is less than 1 (negative or zero) or if the number is greater than 2

Again, suppose if $total is 25, the script may return 1, 2 and 3 for $page=1, $page=2 and $page=3 respectively. It should also return 1 if the input number is less than 1 (negative o开发者_开发百科r zero) or if the number is greater than 1


Here's one way to calculate it:

// 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;

Further, if you wanted to generate an array containing the indexes of each available page you could just do this:

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

print_r($pages);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜