Home > php教程 > php手册 > 记录一下PHP数组数据分页的方法

记录一下PHP数组数据分页的方法

WBOY
Release: 2016-06-13 09:39:13
Original
961 people have browsed it

我们的数据未必都是存储在数据库中,很多时候是用数组来组织的。所以获取数组数据,进行分页是比较常见的编程要求。分页的原理很简单,就是按分页数获取某个范围的数据而已,PHP给我们提供了一个很便利的函数:array_slice()。array_slice() 函数在数组中根据条件取出一段值,并返回。

下面举两个分页例子,都很简单。

	public function books($pagenum = 1)
	{
		include_once("page.php");
		include("arr_books.php");
		
		foreach ($data['books'] as $key=>$value){
			$name[$key] = $value['name'];
			$rank[$key] = $value['rank'];
		}
		
		array_multisort($rank,SORT_NUMERIC,SORT_DESC,$data['books']); 	// 倒序
		//array_multisort($rank,SORT_NUMERIC,SORT_ASC,$data['books']);	// 顺序
		
		$perpage = 10;
		$count = count($data['books']);
		$pages = new PageClass($count, $perpage, $pagenum, base_url().'veda/books/{page}/');
		$start = ($pagenum - 1) * $perpage;
		$data['bks'] = array_slice($data['books'], $start, $perpage);

		$data['nav'] = $pages -> myde_write($pagenum);
		
		$this->load->view('header', $data);
      	$this->load->view('books', $data);
      	$this->load->view('footer', $data);
	} 
Copy after login

再来一个:

$perpage = 2;
$page = intval(getgpc('page')) ? intval($_G['gp_page']) : 1;
$start = ($page - 1) * $perpage;
$count = count($group_list);
$list = array_slice($group_list, $start, $perpage);
$multipage = multi($count, $perpage, $page, "home.php?mod=space&do=group&type=".getgpc('type'));
Copy after login

array_slice() 函数

array_slice() 函数在数组中根据条件取出一段值,并返回。如果数组有字符串键,所返回的数组将保留键名。

语法:array_slice(array,offset,length,preserve)

参数描述
array必需。规定输入的数组。
offset

必需。数值。规定取出元素的开始位置。

如果是正数,则从前往后开始取,如果是负值,从后向前取 offset 绝对值。

length

可选。数值。规定被返回数组的长度。

如果是负数,则从后向前,选取该值绝对值数目的元素。如果未设置该值,则返回所有元素。

preserve

可选。可能的值:

  • true - 保留键
  • false - 默认 - 重置键

例子 1:

<?php
$a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird");
print_r(array_slice($a,1,2));
// Array ( [0] => Cat [1] => Horse )
?>
Copy after login

例子 2(带有负的 offset 参数):

<?php
$a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird");
print_r(array_slice($a,-2,1));
// Array ( [0] => Horse )
?>
Copy after login

例子 3(preserve 参数设置为 true):

<?php
$a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird");
print_r(array_slice($a,1,2,true));
// Array ( [1] => Cat [2] => Horse )
?>
Copy after login

例子 4(带有字符串键):

<?php
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse","d"=>"Bird");
print_r(array_slice($a,1,2));
// Array ( [b] => Cat [c] => Horse )
?>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template