search
HomeBackend DevelopmentPHP TutorialDetailed explanation of array paging implementation in PHP (non-database)

In the 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 <p>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. </p><p>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) </p><h2 id="array-slice">array_slice</h2><p>The first, most basic and most common paging method is to use the array_slice() function. Its function is to intercept a piece of content from an array and return an array of this content. </p><pre class="brush:php;toolbar:false">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 less often, and probably no one knows about it, but in fact the LimitIterator class It has been 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 parameters are wrong

Next, let’s take a look at what will happen to these operations if the parameters are wrong, that is, there is a problem with the offset or the required data size. Such performance.

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 directly returns error exception information for data with wrong offset. This is also the benefit of class mode processing. Any errors will be returned in the form of exceptions, which facilitates our subsequent processing of exceptions.

You can also detect other tests by yourself, such as when the offset is 0 or a negative number, and when the data amount is 0 or a negative number. I won’t write more about these. You can first guess what the results will be based on your existing knowledge, and then write your own code to verify that the results are in line with your expectations. The learning effect will be great! (There is a test in the test code link below, and the result is that there are pitfalls)

总结

一个功能使用了三种方式来实现,这就是代码的魅力。至于哪个好哪个坏我们不多做评价,一切都是以业务为核心来进行选取。类似的功能虽说并不常见,但很多项目里都会遇到,比如说后台用户组管理就会非常常见,一般来说后台用户分组如果不是特别大型的 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

参考文档:

https://www.php.net/manual/zh/function.array-slice.php
https://www.php.net/manual/zh/function.array-chunk.php
https://www.php.net/limititerator

推荐学习:《PHP视频教程

The above is the detailed content of Detailed explanation of array paging implementation in PHP (non-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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.