问题描述
我是这里的新手,想问一下PHP循环
我想从myendpoint获取“ itemid”并将其存储到$result_array
Myendpoint具有分页
第一页,offset=0
,第二页,offset=100
,等等
第一页上的最大id为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);
解决方法
一个非常简单的错误:您在循环外构建该URL时,一遍又一遍地使用相同的URL。将其移入循环,使其包含您正在该循环中计算的$offset