search
HomeBackend DevelopmentPHP ProblemHow 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.

How to implement array paging in PHP without using a database

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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)