愿你坚持不懈,努力进步,进阶成自己理想的人

—— 2017.09, 写给3年后的自己

PHP分页算法

做项目的时候经常用到分页功能,所以自己设计了一个分页算法:

/**
 *  分页算法
 *  
 *  @param $sum - 数据总条数
 *  @param $pagesize - 单页条目
 *  @param $current - 当前页面的页码
 *  @param $url - 页码地址
 */
function multi($sum, $pagesize, $current, $url = "") {
    if(strpos($url, "#")) {
        list($url, $anchor) = explode("#", $url);   
        if($anchor!="") $anchor = "#".$anchor;
    }
        
    $amounts = ceil($sum/$pagesize);
    $extraurl = strpos($url, "?") ? $url."&page=" : $url."?page=";
    
    if($amounts <= 1) {
        return FALSE;
    } else {
        $tofirst = FALSE;
        $tolast  = FALSE;
        
        if($amounts <= 10) {
            $left  = 1;
            $right = $amounts;
        } else {
            if($current+4 <= 10) {
                $left = 1;
                $right = 10;
            } elseif($amounts - $current <= 4) {
                $left  = $amounts - 9;
                $right = $amounts;
            } else {
                $left  = ($current - 5) > 0 ? ($current - 5) : 1;
                $right = ($current + 4) < $amounts ? ($current + 4) : $amounts;
            }
        }
        
        $return = '<div class="pagelist">';
        if($current!=1) $return .= '<a class="page-block" href="'.$extraurl.($current-1).$anchor.'"><</a>';
        if($left!=1) $return .= '<a class="page-block" href="'.$extraurl.'1'.$anchor.'">1..</a>';
        for($i = $left; $i <= $right; $i++) {
            if($i == $current) {
                $return .= '<a class="cur-page-block" href="javascript:;">'.$i.'</a>';  
            } else {
                $return .= '<a class="page-block" href="'.$extraurl.$i.$anchor.'">'.$i.'</a>';
            }
        }
        if($right!=$amounts) $return .= '<a class="page-block" href="'.$extraurl.$amounts.$anchor.'">..'.$amounts.'</a>';;
        if($current!=$amounts) $return .= '<a class="page-block" href="'.$extraurl.($current+1).$anchor.'">></a>';
        $return .= '</div>';
        return $return;
    }
}