【问题标题】:PHP Curl Do While Loop on Pagination with Limit and OffsetPHP Curl 使用限制和偏移在分页上执行 While 循环
【发布时间】:2020-10-20 14:32:32
【问题描述】:

我是这里的新手,想问一下PHP循环

我想从 myendpoint 获取 'itemid' 并将其存储到 $result_array

我的端点有分页

第一页,offset=0,第二页,offset=100,等等

第一页的 itemid 最大值为 100,第二页为 100,等等

最后一页未知,所以我将count($result_array) % 100 == 0设置为while条件

逻辑是如果第一页包含100 itemid,则执行第二页,如果第二页包含100 itemid,则执行第三页,等等

我的脚本只有在第一页包含

如何解决?

谢谢。

这是我的脚本:

$limit = 100;
$offset = 0;

$result_array = array();

$url = 'https://myendpoint/?limit=' . $limit . '&offset=' . $offset;

do {

   $ch = curl_init($url);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

   $response = curl_exec($ch);

   $data = json_decode($response, true);

   curl_close($ch);

   $itemIds = array();
   foreach ($data["items"] as $row) {
       $itemIds[] = $row["itemid"];
   }

   $result_array = array_merge($result_array, $itemIds);

   $offset = $offset + $limit;

} while (count($result_array) % 100 == 0);

print_r($result_array);

【问题讨论】:

  • 您尝试过什么检查为什么脚本不适用于更多项目?

标签: php loops while-loop pagination


【解决方案1】:

非常简单的错误:您一遍又一遍地使用相同的 URL,因为您在循环之外构建它。将其移动到您的循环中,使其包含您在该循环中计算的$offset

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    • 1970-01-01
    相关资源
    最近更新 更多