分页类

 1 <?php
 2 
 3 
 4 class PageTool{
 5     protected $total =0;
 6     protected $perpage = 10;
 7     protected $page = 1;
 8 
 9 
10     public function __construct($total,$perpage =false,$page=false){
11         $this->total = $total;
12         if($perpage){
13             $this->perpage = $perpage;
14         }
15 
16         if($page){
17             $this->page = $page;
18         }
19     }
20     //重要的参数都已拿到,开始创建分页导航,创建分页导航两个步骤,一是保存地址栏参数,二是根据总页数和当前页数计算导航链接,先保存地址栏参数
21     public function show(){
22         $cnt = ceil($this->total/$this->perpage);
23         //分析url地址参数,去掉里面的page,
24         $url = $_SERVER['REQUERST_URI'];/*得到诸如 baidu.com?id=3&cat=5$page=99
25         //拿到带参数的地址栏后用parse_url()函数把上面路径拆成数组array(
26                                                                             [path] =>baidu.com
27                                                                             [query] =>id=3&cat=5$page=99
28 */
29         $parse = parse_url($url);
30          //判断有没有参数,也就是数组中有没有query,有了把它再拆开,用parse_str()函数
31          $param =array();
32          if(isset($parse['query'])){
33             $param = parse_str($parse['query']);/*array(
34                                                                                     [id]  = 3,
35                                                                                     [cat]=5,
36                                                                                     [page] =99
37          */
38          }
39 
40         //去掉里面的page参数,不管有没有都unset下,
41         unset($param['page']);
42 
43         $url = $parse['path'] . '?';
44 
45         if(!empty($param)){
46             $param = http_build_query($param);//重新拼成id=3&cat=5
47             $url =$url .$param . '&'; //baidu.com?id=3&cat=5
48         }
49 
50           $nav = array();
51         $nav[0] = '<span class="page_now">' . $this->page . '</span>';
52 
53                for($left = $this->page-1,$right=$this->page+1;($left>=1||$right<=$cnt)&&count($nav) <= 5;) {
54 
55             if($left >= 1) {
56                 array_unshift($nav,'<a href="' . $url . 'page=' . $left . '">[' . $left . ']</a>');
57                 $left -= 1;
58             }
59 
60             if($right <= $cnt) {
61                 array_push($nav,'<a href="' . $url . 'page=' . $right . '">[' . $right . ']</a>');
62                 $right += 1;
63             }
64         }
65 
66 
67 
68         return implode('',$nav);
69     }
70 
71 }

 

posted @ 2014-10-30 23:19  王孙将归  阅读(150)  评论(0编辑  收藏  举报