It is sometimes necessary to perform paging on an array by calculating the array size, calculating the offset by pagination, and then traversing the page size data from the start offset. Now there is no such trouble, the original PHP function has a ready- array_chunk
made function can be used with us to implement an array of pagination.
array_chunk
Splits an array into multiple
Description
arrayarray_chunk(array$array,$size[,$preserve_keysfalse])
Splits an array into multiple arrays, where the number of cells per array is determined by size. The number of cells in the last array may be less than size.
Sample code
$page=isset($_get[' page '])?(int)$_get[' page ']:1;$pageSize=3;$arr=[1,2,3,4,5,6,7,8,9,Ten];$totalPages=Ceil(Count($arr)/$pageSize);$data=Array_chunk($arr, $pageSize);$msg='';$result=[];if($page>=$totalPages){$msg=' No more data! ';}Else{$result=$data[$page];}Echo Json_encode([' ERROR '=0, ' Data '=$result, ' msg '=$msg]);
Execution results
Resources
- 1, Php:array_chunk-manual
The Array_chunk of PHP functions