分頁查詢 翻轉limit

/**
 * 翻頁使用 大數據order 翻轉limit算法 因爲sql排序翻轉了 所以在外部數據要自己翻轉回來 用array_reverse()即可
 * @param int $total 數據總數
 * @param int $cut_start 截取開始 例如sql裏的 limit 10,20 $cut_start就是10
 * @param int $cut_num 截取個數 limit 10,20 $cut_num 就是20
 * @param bool $desc 排序方式是倒敘 區分倒敘和正序
 * @return bool or [int 截取開始數,int 截取個數,string 倒敘正序]
 */

function big_limit_handle($total,$cut_start,$cut_num,$desc=true)
{
    $mid = floor ( $total / 2 );
    //如果大於間隔 則翻轉
    if ( $cut_start > $mid ) {
        $desc = !$desc;
    }else{
        return false;
    }

    //下面是翻轉算法

    $h_limit = $total - ( $cut_start + $cut_num );

    $h_cut_num=$cut_num;

    //如果小於0說明是最後一頁
    if($h_limit<0){
        $h_limit=$cut_num+$h_limit;
        $h_cut_num=$h_limit;
        $h_limit=0;
    }

    if ( $desc ) {
        $order = 'desc';
    } else {
        $order = 'asc';
    }

    $return = array(
        'limit' => $h_limit,
        'h_cut_num'=>$h_cut_num,
        'order' => $order ,
    );

    return $return;
}

 

用法

$sql = "SELECT count(*) as num FROM  `comment_data` c  $join  where " . $where;

$this->comment_data_db->query ( $sql );
$num = $this->comment_data_db->fetch_array ();

$total=( isset( $num[ 0 ][ 'num' ] ) ? $num[ 0 ][ 'num' ] : 0 );
$cut_num=20;

$cache_data[ 'pages' ] = pages ( $total , $page , $cut_num );

$limit=( $page - 1 ) * $cut_num;

/*翻轉算法start*/
$big_limit_handle=big_limit_handle($total,$limit,$cut_num,true);
$id_order='DESC';
if($big_limit_handle){
    $id_order=$big_limit_handle['order'];
    $limit=$big_limit_handle['limit'];
    $cut_num=$big_limit_handle['h_cut_num'];
}
/*翻轉算法end*/

$where = "SELECT $fields FROM  `comment_data` c  $join  where  " . $where . " ORDER BY {$support_desc}id $id_order limit " . $limit . ",$cut_num";


$this->comment_data_db->query ( $where );
$cache_data[ 'data' ] = $this->comment_data_db->fetch_array ();
if($big_limit_handle){
    $cache_data[ 'data' ]=array_reverse($cache_data[ 'data' ]);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章