简体   繁体   English

我将如何遍历此API数据

[英]How would I loop through this API data

I have an API I'm requesting data from. 我有一个API,我要从中请求数据。

The thing is I don't want to stress my application since the data set can contain tens of thousands of objects. 事情是我不想强调我的应用程序,因为数据集可以包含成千上万的对象。

The way the data is returned is like this where I can specify a page limit and an offset, like limit=10 and offset=10: 数据返回的方式是这样的,我可以指定页面限制和偏移量,例如limit = 10和offset = 10:

"objects": {
    "object",
    "object2",
    //and so on....
}
"hasMore": true,
"count": 23123,

The count property holds the total amount of objects, and hasMore equals true if there's more objects to fetch and false if no objects left. count属性保存对象的总数,如果要提取的对象更多,则hasMore等于true;如果没有对象,则hasMore等于false。

If hasMore equals true my assumption is that I need to make a new request with the offset equal to double my pagesize until hasMore equals false, right? 如果hasMore等于true,我的假设是我需要发出一个偏移量等于页面大小两倍的新请求,直到hasMore等于false,对吗?

I've tried something like this, but no work since I'm left with an almost empty object with only the hasMore equal false and total count: 我已经尝试过类似的操作,但是由于我只剩下hasMore等于false和total count的几乎为空的对象,因此没有任何工作:

 $pageSize = 10;
 $pages = ceil(23123 / $pageSize); // total count of objects
 for ($page = 0; $page <= $pages; $page++) {
    $products = $api->get_products($page * $pageSize, $pageSize);
    var_dump(json_decode($products));
 }

Should work 应该管用

$products = json_decode($products, true)

foreach ($products["objects"] as $object) {
    echo $object;
}

Concur with @miken32 同意@ miken32

Assuming it's $api->getproducts( $offset, $limit ) , try this: 假设它是$api->getproducts( $offset, $limit ) ,请尝试以下操作:

$pageSize      = 10;
$currentPage   = 0;
$hasmore       = true;

while( $hasmore === true ) {
    $currentOffset = $currentPage * $pageSize;
    $products      = json_decode( $api->get_products( $currentOffset, $pageSize ), true );
    $hasmore       = $products['hasMore'];
    processProducts( $products['objects'] );
    $currentPage++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM