網上有很多這篇文章內容,我只是拿過來修改了一下幾個參數,以便容易讀懂
可以自動適應範圍的頁碼分頁程序,頁碼格式如下
<< < 1 2 3 4 5 6 7 > >>
<< < 6 7 8 9 10 11 12 > >>
<?php
/*
* @param $pageid 當前$_GET獲得的頁碼
* @param $total 總記錄數
* @param $uri 頁碼連接文件名
* @param $perpage 每頁顯示
* @param $pagelen 最多顯示幾個頁碼 注意(奇數),對稱嘛!
* return 函數返回一個數組:
* pagecode 索引對應的內容是 生成的HTML 代碼
* sqllimit 索引對應的是sql limit 後綴
*/
function page($pageid,$total,$uri,$perpage=10,$pagelen=7){
$pagecode = ''; # 定義變量,存放分頁生成的HTML
$pageid = intval($pageid); # 避免非數字頁碼
$total = intval($total); # 保證總記錄數值類型正確
if(!$total) return array(); # 總記錄數爲零返回空數組
$pages = ceil($total/$perpage);# 計算總分頁
if($pageid<1) $pageid = 1; # 處理頁碼合法性
if($pageid>$pages) $pageid = $pages;
$offset = $perpage*($pageid-1); # 計算查詢偏移量
//頁碼範圍計算
$init = 1; # 起始頁碼數
$max = $pages; # 結束頁碼數
$pagelen = ($pagelen%2) ? $pagelen : $pagelen+1; # 頁碼個數
$pageoffset = ($pagelen-1)/2; # 頁碼個數左右偏移量
//生成html
$pagecode ='<div class="page">';
$pagecode .="<span>$pageid/$pages</span>"; # 第幾頁,共幾頁
if($pageid!=1){ # 如果是第一頁,則不顯示第一頁和上一頁的連接
$pagecode.="<a href=\"{$uri}?pageid=1\"><<</a>"; # 第一頁
$pagecode.="<a href=\"{$uri}?pageid=".($pageid-1)."\"><</a>";# 上一頁
}
if($pages>$pagelen) { # 分頁數大於頁碼個數時可以偏移
if($pageid<=$pageoffset) {//如果當前頁小於等於左偏移
$init = 1;
$max = $pagelen;
} else { # 如果當前頁大於左偏移
if($pageid + $pageoffset>=$pages+1) { # 如果當前頁碼右偏移超出最大分頁數
$init = $pages-$pagelen+1;
} else { # 左右偏移都存在時的計算
$init = $pageid-$pageoffset;
$max = $pageid+$pageoffset;
}
}
}
//生成html
for( $i=$init; $i<=$max; $i++ ) {
if( $i==$pageid ) {
$pagecode .= '<span>'.$i.'</span>';
} else {
$pagecode .= "<a href=\"{$uri}?pageid={$i}\">$i</a>";
}
}
if($pageid!=$pages){
$pagecode .= "<a href=\"{$uri}?pageid=".($pageid+1)."\">></a>"; # 下一頁
$pagecode .= "<a href=\"{$uri}?pageid={$pages}\">>></a>"; # 最後一頁
}
$pagecode .= '</div>';
return array('pagecode'=>$pagecode,'sqllimit'=>' limit '.$offset.','.$perpage);
}
?>