PHP从巨大的JSON array_chunk分页到多个文件并获取偏移量



所以我有一个有45K+数组的巨大文件,我不能在实时服务器上打开一个巨大的文件,每个请求的流量都很高,所以我使用了array_chunk($array, 1000)并将它们保存在46个文件中。

现在我想在访问特定页面时读取这些文件。

问题?

$offset似乎可以很好地处理某些页面,但主要是偏移- number(负数(的更改。已检查页面25, 50, 75及更多。。。

我的数学有点(非常(弱,所以任何帮助都将不胜感激。谢谢

<?php
$page = ! empty( $_GET['page'] ) ? (int) $_GET['page'] : 1;
$limt = 40;  //Page array/item limit
$fcnt = 46; //Total number of files
$tarr = 45187; //Total number of arrays
$fmu0 = (int)($limt*$fcnt*$page/$tarr); //Getting the file number according to page number
if(file_exists("$fmu0.json")){
$id = json_decode(file_get_contents("$fmu0.json"),true); 
//Each file has 1000 arrays except the last file which has 187 arrays
$tpgs = ceil($tarr/$limt); //Total number of pages
$mult = $fmu0*count($id);
$offset = ($page - 1) * $limt-$mult;
if( $offset < 0 ){$offset = 0;}
$id = array_slice( $id, $offset, $limt );
var_dump($id);
}
?>

每个文件1000个对象,每页40个对象,每个文件25页。

以下是如何查找包含$page编号对象的文件:

$fmu0 = floor($page / 25);

以下是当第一页为1:时,如何在该文件中找到与$page编号对应的40个($limt(对象组的起始索引

$offset = (($page - 1) * $limt) - ($fmu0 * 1000);

<?php
$page = (!empty($_GET['page']) && 0 < $_GET['page'])
? (int)$_GET['page']: 1;
$limt = 40;  //Page array/item limit
// FIND FILE, 25 pages per file
$fmu0 = floor($page / 25);
if(file_exists("$fmu0.json")){
$id = json_decode(file_get_contents("$fmu0.json"),true);     
// FIND GROUP of 40 ($limt) page objects, 1000 objects per file
$offset = (($page - 1) * $limt) - ($fmu0 * 1000);
$id = array_slice( $id, $offset, $limt );
var_dump($id);
}
?>

最新更新