分享一个自己常用的php分页函数,大家可以收藏以后方便使用,代码如下:
/**
* @author maijiawei <632157268@qq.com>
* @param int $total 总数
* @param int $num 显示数量
* @param int $page 当前页码
* @param string $url URL demo:index.php?page=
* @param string $anchor 描 demo:#comment
* @return string 页码html
*/
function pagination($total, $num, $page, $url, $anchor = '') {
$page_show_num = 5; //显示数量
$page_total = @ceil($total / $num); //总页数
if($page_total<=1){
return '';
}
$page_arr = array(); //页码以数组保存
$html = '';
//上页
if($page<=1){
$html .= "<span class=/"page_pre/">上页</span>";
}else{
$page_pre = $page-1;
$html .= "<a class=/"page_pre/" href=/"$url$page_pre$anchor/">上页</a>";
}
$left_num = @ceil($page_show_num / 2); //左边显示数量
$check_num = 0;
for($i=1;$i<=$left_num;$i++){ //获取左边页码
$p = $page-$i;
if($p>0){
$page_arr[]=$p;
$check_num++;
}
}
$left_not_num = $left_num-$check_num; //如果当前页码是1,左边页码是3,那么还有2个页码未获得,右边的页码就加上2
$right_num = $page_show_num-$left_num+$left_not_num; //右边显示数量
$check_num = 0;
for($i=1;$i<=$right_num;$i++){ //获取右边页码
$p = $page+$i;
if($p<=$page_total){
$page_arr[]=$p;
$check_num++;
}
}
$right_not_num = $right_num-$check_num;
$left_num = @ceil($page_show_num / 2)+$right_not_num; //左边显示数量
$check_num = 0;
for($i=1;$i<=$left_num;$i++){ //获取左边页码
$p = $page-$i;
if($p>0){
$page_arr[]=$p;
$check_num++;
}
}
//加第1,2 AND 最后一页和最后两页 AND 当前页
$page_arr[] = $page;
$page_arr[] = 1;
$page_arr[] = 2;
$page_arr[] = $page_total-1;
$page_arr[] = $page_total;
$page_arr = array_unique($page_arr); //去除重复页码
sort($page_arr); //页码排序 小到大
foreach($page_arr as $k => $v){
if($page==$v){ //当前页
$html .= " <span>$v</span> ";
continue;
}
if($v==$page_total-1 and $page<$page_total-$right_num-2){
$html .= "<em>...</em>";
}
$html .= " <a href=/"$url$v$anchor/">$v</a> ";
if($v==2 and $page>=$left_num+4){
$html .= "<em>...</em>";
}
}
if($page>=$page_total){
$html .= "<span class=/"page_next/">下页</span>";
}else{
$page_next = $page+1;
$html .= "<a class=/"page_next/" href=/"$url$page_next$anchor/">下页</a>";
}
return $html;
}
新闻热点
疑难解答