Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Ellipsis in PHP Pagination

Tags:

php

pagination

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

like image 698
user311509 Avatar asked Aug 20 '11 11:08

user311509


2 Answers

$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 "... ";
  }
}
like image 58
user1927675 Avatar answered Oct 19 '22 14:10

user1927675


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 '...';
like image 33
cwallenpoole Avatar answered Oct 19 '22 13:10

cwallenpoole