我需要使用PHP对一些JSON结果进行分页,但是根据我的代码,它无法正常工作。我在下面解释我的代码。
<?php
$arr='[{"sku":"Pizza001","position":0,"category_id":"67"},{"sku":"Birthday Cake","position":0,"category_id":"67"},{"sku":"Birthday Cake-1","position":0,"category_id":"67"},{"sku":"Fruit cake","position":0,"category_id":"67"},{"sku":"Birthday Cake for Gift","position":0,"category_id":"67"}]';
$raw_data = json_decode($arr, true);
paginate($raw_data,1);
function paginate($data, $page = 2, $perPage = 2) {
$x = ($page - 1) * $perPage;
$z = $page * $perPage;
$y = ($z > count($data)) ? count($data) : $z;
for(; $x < $y; $x++) {
print_r($data[$x]);
}
}
?>
在这里,我总是从JSON对象获取第一个2 set o数据。我需要根据$page and $perPage
进行数据过滤。假设$page=1 and $perPage=2
,则将提取记录的前2组,如果$page=2 and $perPage=2
,则将提取接下来的2组(i.e-from 2nd index
),依此类推。请帮助我解决此问题。
答案 0 :(得分:0)
我使用了array_slice
的简单逻辑,正如Wenchoeng Young所建议的那样。
$i=0;
$page=5;
$perPage=1;
$arr='[
{"sku":"Pizza001","position":0,"category_id":"67"},
{"sku":"Birthday Cake","position":0,"category_id":"67"},
{"sku":"Birthday Cake-1","position":0,"category_id":"67"},
{"sku":"Fruit cake","position":0,"category_id":"67"},
{"sku":"Birthday Cake for Gift","position":0,"category_id":"67"}
]';
$raw_data = json_decode($arr, true);
paginate($raw_data, $page, $perPage);
function paginate($data, $page, $perPage)
{ print_r(array_slice($data, $page-1, $perPage)); }
答案 1 :(得分:-1)
使用动态变量作为页码,并限制每页的记录。单击页码后,它会自动更改结果。
<?php
$arr = '[{"sku":"Pizza001","position":0,"category_id":"67"},{"sku":"Birthday Cake","position":0,"category_id":"67"},{"sku":"Birthday Cake-1","position":0,"category_id":"67"},{"sku":"Fruit cake","position":0,"category_id":"67"},{"sku":"Birthday Cake for Gift","position":0,"category_id":"67"}]';
$raw_data = json_decode($arr, true);
paginate($raw_data, 1);
function paginate($data, $page = $pageNumber, $perPage = $limit)
{
$x = ($page - 1) * $perPage;
$z = $page * $perPage;
$y = ($z > count($data)) ? count($data) : $z;
for (; $x < $y; ++$x) {
print_r($data[$x]);
}
}