I am looking for a php json pagination method/class. Here is my code. How to make each 2 json data as a group, for a pagination?
$body = file_get_contents("out_file.txt");
$json = json_decode($body,true);
foreach($json as $data){
echo $data['name'].' ';
}
out_file.txt
[
{"name":"text1","num":"1"},
{"name":"text2","num":"2"},
{"name":"text3","num":"3"},
{"name":"text4","num":"4"},
{"name":"text5","num":"5"},
{"name":"text6","num":"6"}
]
I need divide data like this:
page1
text1 text2
page2
text3 text4
page3
t开发者_开发百科ext5 text6
json_decode($body,true)
returns an array of associative arrays in place of the JSON objects specified in your file. Knowing that you have an array containing all the elements you want to cycle through you can use a generic pagination function to control which data is displayed. Something like...
$body = file_get_contents("out_file.txt");
$json = json_decode($body,true);
paginate($json,$pageNumber);
function paginate($data, $page = 1, $perPage = 2) {
$x = ($page - 1) * $perPage;
$z = $page * $perPage;
$y = ($z > count($data)) ? count($data) : $z;
for(; $x < $y; $x++) {
echo $data[$x]['name'];
}
}
JSON data is not a "display" medium... it's a data transfer format. How you do pageination of the data within the JSON body is up to you, but that's true of ANY data structure, not just JSON. Given that your sample JSON structure is an array, you'd simply do some array indexing with your "page" offsets:
$page = 2;
$items_per_page = 2;
echo $json[$page * $items_per_page]['name'] // $json[4] -> text5
echo $json[$page * $items_per_page + 1]['name'] // $json[5] -> text6
精彩评论