自定义分页类,可根据需要格式修改
程序员文章站
2024-02-20 19:14:28
...
在使用yii框架做分页时,发现yii框架本身自带的分页方法不支持我所需要的格式
<?php
/**
* 分页类
*/
class Page
{
private $count; // 总条数
private $size = 10; // 每页显示条数
private $num; // 总页数
private $curr; // 当前页
private $offset = 3; // 偏移量(步长)
private $config = array(
'last' => '<<',
'next' => '>>',
);
private $param;
public function __construct($count,$size=10)
{
$this->count = $count;
$this->size = $size;
$this->curr = isset($_GET['p']) ? $_GET['p'] : 1 ;
$this->param = $_GET;
}
/**
* 获取分页码
*
* @author BING
* @return string
*/
public function show()
{
$this->num = $num = ceil($this->count / $this->size);
// 计算左侧页码
$leftPage = max($this->curr - $this->offset,1);
// 计算右侧页码
$rightPage = min($this->curr + $this->offset,$num);
// 处理URL参数
$httpParam = $this->httpBuild();
// 上一页
$lastPage = '';
if($this->curr > 1)
{
$lastNum = $this->curr - 1;
$lastPage = '<a href="?'.$httpParam.'&p='. $lastNum .'">'.$this->config['last'].'</a> ';
}
// 下一页
$nextPage = '';
if($this->curr < $num)
{
$nextNum = $this->curr + 1;
$nextPage = '<a href="?'.$httpParam.'&p='. $nextNum .'">'.$this->config['next'].'</a> ';
}
// 分页链接
$pageLink = '';
for($i=$leftPage; $i <= $rightPage; $i++)
{
$pageLink .= ' <a href="?'.$httpParam.'&p='.$i.'">'.$i.'</a> ';
}
$head = '第'. $this->curr. '页/共'. $this->num .'页';
return $head.$lastPage.$pageLink.$nextPage;
}
// 设置分页样式
public function setConfig($config)
{
foreach ($config as $key => $value)
{
$this->config[$key] = $value;
}
}
protected function httpBuild()
{
if(isset($this->param['p']))
{
unset($this->param['p']);
}
return http_build_query($this->param);
}
}
?>
推荐阅读