PHP分页-限制链接数量


PHP Pagination - Limit amount of links

所以我有这样的分页链接。

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

链接增长为:

1 2 3 4 5 6 7等等

但我想限制这一点,所以如果有超过7页,它将只显示7个链接,如下所示:

1 2 3。。。10 11 12

其中12是最后一页。

如果你转到下一页,它只会像这样更改前几页:

3 4 5。。。10 11 12

直到你到达最后7页,像这样:

6 7 8 9 10 11 12

我该怎么做??

请帮忙。

这里有一种方法。

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

这允许更改显示的链接数,即从7个更改为9个。

注意,在round()中使用PHP_ROUND_HALF_DOWN需要php>=5.3