search
HomeBackend DevelopmentPHP TutorialHow to paginate a two-dimensional array in php (with code)

The content of this article is about how to paginate two-dimensional arrays in PHP (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Paging a two-dimensional array, assuming that 10 items are displayed on each page, the paging of a list is usually checked from the database, and it is found to be a two-dimensional array, and then rendered to the list. The paging here is to check the database. When checking, only the number of items per page is checked. If there are ten items on each page, only ten items are checked. However, this two-dimensional array is not found from the database, but all the data is stored in this array from the beginning. To render to a list, how to paginate? There is a stupid way, through subscripts, select ten one-digit arrays from this two-digit array through subscripts, and reassemble a two-digit array. Assume a two-dimensional array as follows, for each page 10 items can display two pages, so I made 12 items of data

$arr = array(
				array('name'=>'第一页张三1','mobile'=>'111111111'),
                array('name'=>'第一页李四1','mobile'=>'222222222'),
                array('name'=>'第一页王五1','mobile'=>'333333332'),
                array('name'=>'第一页李四2','mobile'=>'444444444'),
                array('name'=>'第一页张三2','mobile'=>'555555555'),
                array('name'=>'第一页王五2','mobile'=>'666666666'),
                array('name'=>'第一页张三3','mobile'=>'777777777'),
                array('name'=>'第一页李四3','mobile'=>'888888888'),
                array('name'=>'第一页王五3','mobile'=>'999999999'),
                array('name'=>'第一页李四4','mobile'=>'123456789'),
                array('name'=>'第二页张三4','mobile'=>'987654321'),
                array('name'=>'第二页王五4','mobile'=>'112233445'),
			);

			//前端传过来的页数,第几页
			$p = I('p');
			if (empty($p)){
				$p = 1;
			}

			//开始取值的下标,数组下标是从0开始的,例如第一页从下标为0开始取,第二页从下标为10开始取
			$start = ($p-1)*10;

			//根据开始的下标,和需要取的数据的条数(每页显示的条数)循环赋值给新数组
			for ($i=$start;$i<$start+10;$i++){
				if (!empty($arr[$i])){
					$new_arr[$i] = $arr[$i];
				}
			}

            dump($new_arr);

Print the result:

Encapsulate it:

public function arr_page($arr,$p,$count){
        if (empty($p)){
            $p = 1;
        }

        if (empty($count)){
        	$count = 10;
		}

        $start = ($p-1)*$count;
        for ($i=$start;$i<$start+$count;$i++){
            if (!empty($arr[$i])){
                $new_arr[$i] = $arr[$i];
            }
        }

        return $new_arr;
	}

Call: print out the same result

 $new_arr = $this->arr_page($arr,1,10);

 dump($new_arr);

You can also pass other parameters when calling, not necessarily every page Ten items,

$new_arr = $this->arr_page($arr,1,5);
$new_arr = $this->arr_page($arr,2,5);

As for how many pages there are, just use count($arr) divided by the number of items per page. If there are decimals, add 1, so that you can paginate.

The above is the detailed content of How to paginate a two-dimensional array in php (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.