<?php $arr = array(0,1,2,3,4); var_dump(array_slice($arr,0,2)); echo "<br/>"; $arr2 = array('a'=>array('a','a','a'),'b'=>array('b','b','b')); var_dump(array_slice($arr2,0,1)); ?>
返回的结果如下:
array(2) { [0]=> int(0) [1]=> int(1) }
array(1) { ["a"]=> array(3) { [0]=> string(1) "a" [1]=> string(1) "a" [2]=> string(1) "a" } }
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/$perpage); //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><?php echo $v['name']; ?></td> <td><?php echo $v['sex']; ?></td> <td><?php echo $v['job']; ?></td> </tr> <?php } ?> </table> <?php if($page>1){ echo "<a href='?page=1'>首页</a>"; echo "<a href='?page=".($page-1)."'>上一页</a>"; } if($page<$pages) { echo "<a href='?page=".($page+1)."'>下一页</a>"; echo "<a href='?page=".$pages."'>末页</a>"; } ?>
希望本文所述对大家的PHP程序设计有所帮助。