Add Ellipsis in PHP Pagination

2020-07-09 02:48发布

.
//Prev
. 
for($number = 1; $number <= $num_pages; $number++)
{   
    if($page == $number)
    {
        $navigator .= "<b>[$number]</b> ";
    }
    else
    {
        $navigator .= "<a href='?c=".$_SESSION['cID']".&rows=".$per_page."&page=$number'>$number</a> ";
    }
}
.
//Next
.

This is the snippet that prints number of pages.

Sample output:

Previous 1 2 3 4 [5] 6 7 8 9 10 Next

5 is the current page.

Problem: page numbers are shown in sequence with no restrictions. If i have 100 pages, all numbers show up.

Question: I need my paging numbers appear as the following...

Assume we only have 7 ($num_pages) pages:

Previous 1 2 [3] 4 5 6 7 Next

Assume we have 90 pages:

[1] 2 3 4 5 6 7 ... 90 Next

Assume user clicked the 7th page:

Previous 1 ... 5 6 [7] 8 9 10 11 ... 90 Next

Assume user clicked 11th page:

Previous 1 ... 9 10 [11] 12 13 14 15 ... 90 Next

Assume user clicked 15th page:

Previous 1 ... 13 14 [15] 16 17 18 19 ... 90 Next

Assume user clicked 90th page:

Previous 1 ... 84 85 86 87 88 89 [90]

Any help will be appreciated.

3条回答
在下西门庆
2楼-- · 2020-07-09 03:40

An elegant solution for this kind of thing is to use "logarithmic page navigation". See my answer to this question (PHP code included):

How to do page navigation for many, many pages? Logarithmic page navigation

查看更多
狗以群分
3楼-- · 2020-07-09 03:41

This should be more than enough to get you started at least

$count = 7; // number to show
// start at half threshold down from the current location.
$number = $current - round($count/2); 
if( $number > 1 ) echo '...';
else $ // increase to have number start at 1.
for( $number; $number < $number + $count; $number++)
{
    // your for loop as normal
}
if( $number < $total ) echo '...';
查看更多
一夜七次
4楼-- · 2020-07-09 03:48
$radius = 3;

for($i = 1; $i <= $total; $i++){
  if(($i >= 1 && $i <= $radius) || ($i > $current - $radius && $i < $current + $radius) || ($i <= $total && $i > $total - $radius)){
    if($i == $current) echo "<b>".$i."</b>";
  }
  elseif($i == $current - $radius || $i == $current + $radius) {
    echo "... ";
  }
}
查看更多
登录 后发表回答