I'm trying to make a pagination where I can limit how many numbers it will show in the navigation so it will be something like this
< 1 ... [3] 4 5 ... 9 >
The script I have now is working fine until I'm at the last couple of pages. Lets say I set max numbers allowed in the navigation to 4 and number of pages to 9. Then it will work to page 7, but from page 7 it will start shrink in numbers and not put them in front of the current page number. It will behave like this
< 1 ... [7] 8 9
< 1 ... [8] 9
When I'm at the last page the navigation will only show
< 1 ... 9
What i would like it to look like is like this
< 1 ... 6 [7] 8 9 >
< 1 ... 6 7 [8] 9 >
< 1 ... 6 7 8 [9]
I have tried to make this work for some hours now but, are kind of stuck. Any suggestions?
// Method to output the pagination
function output_pagination($max_per_page, $table) {
$page_number = $this->valid_page_number($this->get_page_number(), $table); // Get current page number
$num_pages = $this->count_table_rows($table) / $max_per_page; // Set the number of pages
$max_nav_pages = 4; // Max numbers of pages in the page navigation
$start = $page_number-1; // Value to start the loop on
// Set start to 1 if it equals 0
if($start === 0) {
$start = 1;
}
// Keep loop going until $i no longer is greater or equal to number of pages
for($i = $start; $i <= $num_pages; $i++) {
// Output prev arrow + '...' + 1 if its the start of the pagination and page number not equals 1 ($i = 1 and page number is > $i)
if(($i === $start) && ($page_number > 1)) {
// Check if number of pages are greater then max allowed in navigation and if page number not equals 2
if(($num_pages > $max_nav_pages) && ($page_number !== 2)) {
echo "<< ";
echo "< ";
echo "1 ";
echo " ... ";
$i = $page_number - 1;
} else {
echo "<< ";
echo "< ";
echo $i;
}
}
// Output current page in bold text if $i equals or are greater then $start and page number equals $i
else if (($i >= $start) && ($page_number === $i)) {
echo " <b>[".$i."]</b> ";
}
// Output "...", last page number and next page arrow. if we have 10 pages or more. Then break the loop. We are done.
else if($i === $start + $max_nav_pages) {
// Check if page number equals number of pages - max allowed nav pages + 1
if($page_number === $num_pages-$max_nav_pages+1) {
echo $i;
echo " >";
echo " >>";
break;
} else {
echo " ... ";
echo $num_pages;
echo " >";
echo " >>";
break;
}
}
// Output next page number if $i is greater then $start and $i + 1 is equal or greater then number of total pages
else if(($i > $start) && ($i + 1 <= $num_pages)) {
echo " ".$i." ";
}
else { // Output last page number and next page arrow. We are done.
echo $i;
echo " >";
echo " >>";
}
}
}
答案 0 :(得分:1)
Let's say you are in page 8, then the loop always starts from $page_number - 1 which will be 7, which means 6 will never be displayed. You need to start your loop from $page_number - $max_nav_pages and determine which numbers should be displayed that way.