前几天我在做项目的时候,突然感觉有点看不到它调数据的源头,而且当时正在赶进度,于是我就想到了如果利用已经获取到的结果集进行分页。之后,我找到了array_slice函数。非常好用,分享一下:
<?php
//假定一个结果集二维数组:
$arr =array(array('name'=> 'name1','sex' =>'sex1','job' => 'job1'),
array('name'=> 'name2','sex' =>'sex2','job' => 'job2'),
array('name'=> 'name3','sex' =>'sex3','job' => 'job3'),
array('name'=> 'name4','sex' =>'sex4','job' => 'job4'),
array('name'=> 'name5','sex' =>'sex5','job' => 'job5'),
array('name'=> 'name6','sex' =>'sex6','job' => 'job6'),
array('name'=> 'name7','sex' =>'sex7','job' => 'job7'),
array('name'=> 'name8','sex' =>'sex8','job' => 'job8'),
array('name'=> 'name9','sex' =>'sex9','job' => 'job9'),
array('name'=> 'name10','sex' =>'sex10','job' => 'job10'),
array('name'=> 'name11','sex' =>'sex11','job' => 'job11'),
array('name'=> 'name12','sex' =>'sex12','job' => 'job12'),
);
//计算总记录条数
$num =count($arr);
//规定每页显示的条数
$perpage= 3;
//计算页数
$pages= ceil($num/$p————erpage);
//echo $num,$perpage,$pagecount;exit;
if(is_numeric($_REQUEST['page']))
{
if($_REQUEST['page']<1){
$page =1;
}elseif($_REQUEST['page']>$pages)
{
$page =$pages;
}else{
$page =$_REQUEST['page'];
}
}else{
$page = 1;
}
$start = ($page-1)*$perpage;
$newpage =array_slice($arr,$start,$perpage,true);
//print_r($newpage);exit;
?>
<table cellpadding="0" cellspacing="0"border="1">
<tr>
<td>name</td>
<td>sex</td>
<td>job</td>
</tr>
<?php
foreach($newpage as $k =>$v)
{
?>
<tr>
<td><?phpecho $v['name'];?></td>
<td><?phpecho $v['sex'];?></td>
<td><?phpecho $v['job'];?></td>
</tr>
<?php
}
?>
</table>
<?php
if($page>1){
echo "<ahref='?page=1'>首页</a>";
echo "<ahref='?page=".($page-1)."'>上一页</a>";
}
if($page<$pages)
{
echo "<ahref='?page=".($page+1)."'>下一页</a>";
echo "<ahref='?page=".$pages."'>末页</a>";
}
?>
效果如下:
http://localhost/test.php?page=3