How to implement array paging in PHP without using a database
This article will introduce to you how to implement array paging in PHP without using a database. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Array paging implementation in PHP (non-database)
In daily development business environment , we generally use MySQL statements to implement the paging function. However, there are often some data that are not large, or the paging function is only needed to obtain some array data defined in PHP. At this time, we actually don’t need to query the database every time. We can fetch all the data in one query, and then implement the paging function at the PHP code level. Today, we will learn some function techniques that can achieve this capability.
First, we still prepare the test data.
$data = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', ]; // $p = $_GET['p']; $p = 2; $currentPage = $p <= 1 ? 0 : $p - 1; $pageSize = 3; $offset = $currentPage * $pageSize;
Assume \$data is all the data taken out from the database, or the data we have written in the PHP code. Then we set $p as the received request parameter, and the current page being accessed is the second page. $currentPage is used to query the offset correction. In the world of code development, subscript indexes all start from 0, so we need to decrement the received parameters by one. Of course, you can also set the parameters passed by the front end to use 0 as the first page. I won’t explain this much. I believe everyone will understand its meaning as long as they have studied it formally or participated in a development project.
Then we define the number of pieces of information displayed on the current page $pageSize, that is, only 3 pieces of data are obtained. Finally, we calculated the offset, which is similar to the parameter in MySQL's LIMIT. Its function is to tell us which item to start querying from, and then use $pageSize to query how many items. In this way we can get the data corresponding to the current page. (It seems that the principles of paging have been explained)
array_slice
The first and most basic and common paging method is to use the array_slice() function. accomplish. Its function is to intercept a piece of content from an array and return an array of this content.
var_dump(array_slice($data, $offset, $pageSize)); // array(3) { // [0]=> // string(1) "D" // [1]=> // string(1) "E" // [2]=> // string(1) "F" // }
array_slice() function requires three parameters, the second parameter is the offset, and the third parameter is to query several pieces of data. Among them, the third parameter is optional. If not filled in, all data after the currently set offset will be displayed. Is it exactly the same as our MySQL query statement? Yes, they themselves are similar operations.
array_chunk
array_chunk() function groups an array according to a numerical parameter, that is, splits the array into sub-arrays. We can obtain the subarray contents of the specified subscript based on the divided array. These contents are the data that need to be displayed on the current page.
$pages = array_chunk($data, $pageSize); var_dump($pages); // array(4) { // [0]=> // array(3) { // [0]=> // string(1) "A" // [1]=> // string(1) "B" // [2]=> // string(1) "C" // } // [1]=> // array(3) { // [0]=> // string(1) "D" // [1]=> // string(1) "E" // [2]=> // string(1) "F" // } // [2]=> // array(3) { // [0]=> // string(1) "G" // [1]=> // string(1) "H" // [2]=> // string(1) "I" // } // [3]=> // array(2) { // [0]=> // string(1) "J" // [1]=> // string(1) "K" // } // } var_dump($pages[$currentPage]); // array(3) { // [0]=> // string(1) "A" // [1]=> // string(1) "B" // [2]=> // string(1) "C" // }
In this code, we output the contents of the divided array, and then what we need is the second page, which is the data with subscript 1. We can easily obtain the required information directly through the divided array. content. Using this function to do array paging is very simple and intuitive, and it does not need to calculate the offset. You can directly use the current page $currentPage and $pageSize to complete the grouping of data. It is highly recommended that you use this function. Do something similar.
LimitIterator
The last thing we need to learn is the ability to use an iterator class to implement array paging. This is used relatively rarely, and probably not many people use it. I know, but in fact the LimitIterator class was already provided in PHP5.1. Its purpose is to allow iteration over a restricted subset of the elements of an Iterator. In other words, if our code uses the iterator pattern and implements the iterator interface, then these iterator classes can use this class for paging operations.
foreach (new LimitIterator(new ArrayIterator($data), $offset, $pageSize) as $d) { var_dump($d); } // string(1) "D" // string(1) "E" // string(1) "F"
It requires 3 instantiation construction parameters. The first one is an iterator object. Since the array is not an iterator object, we use the ArrayIterator instance to convert our array data into an iterator object. . The next two parameters are the offset and the number of data. This is similar to the array_slice() function, but the difference is that its offset parameter is also optional. If we do not give the following optional parameters, then it will traverse all the data.
foreach (new LimitIterator(new ArrayIterator($data)) as $d) { var_dump($d); } // string(1) "A" // string(1) "B" // string(1) "C" // string(1) "D" // string(1) "E" // string(1) "F" // string(1) "G" // string(1) "H" // string(1) "I" // string(1) "J" // string(1) "K"
Performance when the parameters are wrong
Next, let’s look at what happens if the parameters are wrong, that is, there is a problem with the offset or the required data size, How these operations will behave.
var_dump(array_slice($data, $offset, 150)); // array(8) { // [0]=> // string(1) "D" // [1]=> // string(1) "E" // [2]=> // string(1) "F" // [3]=> // string(1) "G" // [4]=> // string(1) "H" // [5]=> // string(1) "I" // [6]=> // string(1) "J" // [7]=> // string(1) "K" // } var_dump(array_slice($data, 15, $pageSize)); // array(0) { // }
array_slice() function is compatible with offset errors by displaying an empty array. If the amount of data exceeds the standard, all data after the offset will be displayed.
var_dump($pages[15]); // NULL
array_chunk() will of course return a NULL value for data whose subscript does not exist.
foreach (new LimitIterator(new ArrayIterator($data), $offset, 150) as $d) { var_dump($d); } // string(1) "D" // string(1) "E" // string(1) "F" // string(1) "G" // string(1) "H" // string(1) "I" // string(1) "J" // string(1) "K" foreach (new LimitIterator(new ArrayIterator($data), 15, $pageSize) as $d) { var_dump($d); } // Fatal error: Uncaught OutOfBoundsException: Seek position 15 is out of range
LimitIterator 则是对于偏移量错误的数据直接返回错误异常信息了。这也是类模式处理的好处,有错误都会以异常的形式进行返回,方便我们对异常进行后续的处理。
其它的测试大家还可以自行检测,比如偏移是 0 或者是负数的情况,数据量是 0 或者是负数的情况。这些我就不多写了,大家可以根据已有的知识先猜想一下结果会是什么样的,然后再自己写代码验证一下结果是符合自己的预期,这样学习的效果会非常棒哦!(在下方测试代码链接中有测试,结果里面是有坑的哦)
总结
一个功能使用了三种方式来实现,这就是代码的魅力。至于哪个好哪个坏我们不多做评价,一切都是以业务为核心来进行选取。类似的功能虽说并不常见,但很多项目里都会遇到,比如说后台用户组管理就会非常常见,一般来说后台用户分组如果不是特别大型的 ERP 项目都不会很多,但有时候也会达到需要分页的程度,这时候,我们就可以考虑考虑使用今天所学的知识来做咯!
测试代码:
https://github.com/zhangyue0503/dev-blog/blob/master/php/202008/source/PHP%E4%B8%AD%E7%9A%84%E6%95%B0%E7%BB%84%E5%88%86%E9%A1%B5%E5%AE%9E%E7%8E%B0%EF%BC%88%E9%9D%9E%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%89.php
推荐学习:php视频教程
The above is the detailed content of How to implement array paging in PHP without using a database. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
