简体   繁体   English

PHP分页-限制链接数量

[英]PHP Pagination - Limit amount of links

So i have my pagination links like this. 所以我有这样的分页链接。

for ( $counter = 0; $counter <= $page_amount; $counter += 1) {
        echo "<a href=\"section.php?q=$section&p=$counter\">";
        echo $counter+1;
        echo "</a>";
     }

And the links grows like: 链接增长如下:

1 2 3 4 5 6 7 and so on. 1 2 3 4 5 6 7等。

But i want to limit this so if there is more than 7 pages it shall only show 7 links like this: 但我想限制此范围,因此,如果有7个以上的页面,它将仅显示7个这样的链接:

1 2 3 ... 10 11 12 1 2 3 ... 10 11 12

where 12 is the last page. 最后一页是12。

And if you go to next page it will only change the first pages like this: 而且,如果您转到下一页,则只会更改首页,如下所示:

3 4 5 ... 10 11 12 3 4 5 ... 10 11 12

until you reach the last 7 pages like this: 直到您到达最后7页,如下所示:

6 7 8 9 10 11 12 6 7 8 9 10 11 12

How do i do this ?? 我该怎么做呢 ??

please help. 请帮忙。

Here is one way to do it. 这是一种方法。

// Set some presets
$current_page = 0;
$page_amount = 11;
$limiter = 7;

// Set upper and lower number of links
$sides = round(($limiter/2), 0, PHP_ROUND_HALF_DOWN);

for ( $counter = 0; $counter <= $page_amount; $counter++) {
    // Start with Current Page
    if($counter >= ($current_page)){
        // Show page links of upper and lower
        if(($counter <($current_page+$sides))||($counter >($page_amount-$sides))){
            echo "<a href=\"section.php?q=$section&p=$counter\">";
            echo $counter+1;
            echo "</a> ";
        }
        // The middle link
        elseif($counter ==($current_page+$sides)){
            echo "<a href=\"page.php?p=$counter\">";
                    // Show number if number of links == $limiter
            if(($page_amount-$current_page)==$limiter-1){
                 echo $counter+1;
            }
            // Show '...' number of links > $limiter 
                    else {
                     echo "...";
            }
            echo "</a> ";
        }
     }
}

This allows to change the number of links shown, ie. 这允许更改显示的链接数,即。 from 7 to 9. 从7到9。

Note, using PHP_ROUND_HALF_DOWN in round() requires php>=5.3 注意,在round()使用PHP_ROUND_HALF_DOWN需要php> = 5.3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM