关于数组分页问题

很多时候,我们想查询数据的时候想先限制数目,然后再分页,那我们该怎么做呢;

以下是基于thinkphp5.0框架下的做法:

        public function index()
	{
        $result=$m::where($where)
                ->alias('a')
                ->join('gz_jadmin b','a.shenhe_user = b.username')
                ->field("a.*,b.pname")
                ->order("a.login_date desc")
                ->limit(100)
                ->select();
        $count=count($result);
        $pagesize=20;
        $page=empty($_GET['page'])?1:$_GET['page'];
	    $str=$this->page_array($pagesize,$page,$result,0);
	    $pages=$this->show_array('','http://www.xxxx.com/unmap/index/act/'.$act);
        $this->assign("act",$act);
        $this->assign("wd",$wd);
	    $this->assign("mlist",$str);
        $this->assign("subtitle",$subtitle);
        if($count > $pagesize){
            $this->assign("pages",$pages);
        }
	    return $this->fetch();
	} 
	/**   
	 * 数组分页函数  核心函数  array_slice   
	 * 用此函数之前要先将数据库里面的所有数据按一定的顺序查询出来存入数组中   
	 * $count   每页多少条数据   
	 * $page   当前第几页   
	 * $array   查询出来的所有数组   
	 * order 0 - 不变     1- 反序   
	 */ 
	public function page_array($count,$page,$array,$order){
	    global $countpage; #定全局变量      
	    $page=(empty($page))?'1':$page; #判断当前页面是否为空 如果为空就表示为第一页面       
	       $start=($page-1)*$count; #计算每次分页的开始位置      
	    if($order==1){      
	      $array=array_reverse($array);      
	    }         
	    $totals=count($array);        
	    $countpage=ceil($totals/$count); #计算总页面数      
	    $pagedata=array();      
	    $pagedata=array_slice($array,$start,$count);
	    return $pagedata;  #返回查询数据      
	}  
        /**   
	 * 分页及显示函数   
	 * $countpage 全局变量,照写   
	 * $url 当前url   
	 */
	function show_array($countpage,$url){
		global $countpage;
		$page=empty($_GET['page'])?1:$_GET['page'];      
		if($page > 1){
		$uppage=$page-1;
		}else{      
		$uppage=1;      
		}      
		if($page < $countpage){
		$nextpage=$page+1;
		}else{      
		$nextpage=$countpage;      
		}      

		$str='<div class="gj-page">'; 
		$str.="<a href='$url?page=1' class='page-up disable'><span>首页</span></a>";  
        $str.="<a>{$page} / {$countpage} 页</a>";     
		//$str.="<span><a href='$url?page={$uppage}'> 上一页  </a></span>";      
		$str.="<a href='$url?page={$nextpage}' class='page-down'><span>下一页</span></a>";      
		//$str.="<span><a href='$url?page={$countpage}'>尾页  </a></span>";      
		$str.='</div>';      
		return $str;
    }      

2018-02-08 16:56:12 1400人阅读 评论( 0 )