Home >Backend Development >PHP Tutorial >How 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!