PHP分页问题

问题描述:

I'm having a problem with my PHP pagination for a project.

It almost works but it doesn't seem to display the numbers correctly.

I want only 6 more page numbers to display after the selected and one before; (also if you are on page one display 7 after)

For example:

If on Page 1: 1/2/3/4/5/6/7/8

If on Page 2: 1/2/3/4/5/6/7/8

If on Page 5: 4/5/6/7/8/9/10/11

If on Page 10: 9/10/11/12/13/14/15/16

This is my code so far...

if($page == ceil($NumOfPages) && $page != 1){
    for($i = 1; $i <= ceil($NumOfPages)-1; $i++){
    if($i > 0){
        echo "<a href=\"/{$i}\">{$i}</a>";
    }
    }
}
if ($page == ceil($NumOfPages) ) {
    $startPage = $page;
}else{
    $startPage = 1;
}
for ($i = $startPage; $i <= $page+6; $i++){
        if ($i <= ceil($NumOfPages)){
            if($i == $page) {
                echo "<a href='/page/$i/' title='View movies page $i' id='pagelisel'>$i</a> ";
            }else{
                echo "<a href='/page/$i/' title='View movies page $i' id='pageli'>$i</a> ";
            }
        }
}

Any help would be greatly appreciated,

Thanks!

I assumed that (partly for myself... ;) ):

  • $page is the selected page
  • $startPage is the first page number you want to show
  • $numPages is already ceil-ed

First you need to find $startPage. Depending whether $page is the first one (ie has the value one 1, another assumption) or not. Your check is slightly off, as it check if it is equal to the last page.

if($page == 1) {
    $startPage = 1;
} else {
    $startPage = $page - 1;
}

Then you need to find out the last page number you want to print ($lastPage). So check if $startPage is near the end and set ~$lastPage` accordingly:

if($startPage + 7 > $numPages) {
    $endPage = $numPages;
} else {
    $endPage = $startPage + 7;
}

Finally, use you for-loop which seem ok, but loop from $startPage to $endPage.

Here's an alternative approach that should work for you as well:

$pageCurrent = $page;
$pagePrevious = $pageCurrent-1;
$pageClass = '';
$pageStart = 1;
$pageEnd = $pageCurrent+6;
$pageMax = ceil($NumOfPages);

if($pageCurrent==1){
    echo "<a href=\"/page/1\" class=\"selected\">1</a>";
}else{
    echo "<a href=\"/page/$pagePrevious\">$pagePrevious</a>";
}

for($i = $pageStart; $i <= $pageEnd; $i++){
    if($i <= $pageEnd){
        if($i == 1 && $pageCurrent != 1){
            $pageClass = 'selected';
        }else{
            $pageClass = '';
        }
        echo "<a href=\"/page/$i\" title=\"View movies page $i\" class=\"$pageClass\">$i</a>";
    }
}