PHP数组分页

2013-6-7 liyangweb.com 李杨 PHP

今天闲来无事,写了一个数组分页函数,分享给大家,还不是特别完善,函数很简单,有很大的空间可以自由发挥~~~

函数体:


/*
 * @array	所有数据
 * @start_page	开始页数
 * @page_size	每页数量
 */
function array_page($array,$start_page=1,$page_size=5) {
    $array_count = count($array);   //数据总数
    $page_count = ceil($array_count/$page_size);    //总页数
    $start_page = ($start_page < $page_count) ? $start_page : $page_count;	//保证接收来的$start_page在合法的范围内
    $prev = (($start_page - 1) > 0) ? ($start_page - 1) : 1;    //上一页
    $next = (($start_page + 1) <= $page_count) ? ($start_page + 1) : $page_count;   //下一页
    $return_array=array_slice($array,($start_page-1) * $page_size,$page_size);  //当前页面显示的数据
    $page="当前第{$start_page}页<a href='?page=1'>首页</a> <a href='?page={$prev}'>上一页</a> <a href='?page={$next}'>下一页</a> <a href='?page={$page_count}'>尾页</a> 总{$page_count}页";
    $return = array('content'=>$return_array,'page'=>$page);	//content当前页面显示的内容,page分页
    return $return;
}


调用实例:


$array=array("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20");   //所有数据
$start_page = isset($_GET['page'])?$_GET['page']:1;	//当前页
$page_size = 3;	//每页显示3条数据
$return = array_page($array,$start_page,$page_size);
foreach($return['content'] as $content){
	echo $content . '<br>';
}
echo '<hr>';
echo $return['page'];


标签: PHP数组分页

发表评论:

Powered by emlog 冀ICP备13011830号-1