【发布时间】:2020-10-08 13:42:08
【问题描述】:
我的结果数组有问题,我最初想要的是这样的
$promises = [
'0' => $client->getAsync("www.api.com/opportunities?api=key&page=1fields=['fields']"),
'1' => $client->getAsync("www.api.com/opportunities?api=key&page=2fields=['fields']"),
'2' => $client->getAsync("www.api.com/opportunities?api=key&page=3fields=['fields']")
];
一组请求承诺,我将使用它,因为我想从我正在使用的 API 中检索数据集合。这是 API 第一页的样子
在我的请求中,我想获得第 2、3、4 页。 这是第 2 页的样子
我在我的 PHP 脚本上做了一个 do while 循环,但它似乎运行了一个无限循环 这就是它应该如何工作的方式。首先,我运行初始请求,然后获取 totalRecordCount = 154 并将其减去 recordCount = 100 如果差异为 != 0 它再次运行它并更改 $pageNumber 并将其推送到承诺。
这是我的功能代码。这是我的代码
function runRequest(){
$promises = [];
$client = new \GuzzleHttp\Client();
$pageCounter = 1;
$globalCount = 0;
do {
//request first and then check if has difference
$url = 'https://api.com/opportunities_dates?key='.$GLOBALS['API_KEY'].'&page='.$pageCounter.'&fields=["fields"]';
$initialRequest = $client->getAsync($url);
$initialRequest->then(function ($response) {
return $response;
});
$initialResponse = $initialRequest->wait();
$initialBody = json_decode($initialResponse->getBody());
$totalRecordCount = $initialBody->totalRecordCount;//154
$recordCount = $initialBody->recordCount;//100
$difference = $totalRecordCount - $recordCount;//54
$pageCounter++;
$globalCount += $recordCount;
array_push($promises,$url);
} while ($totalRecordCount >= $globalCount);
return $promises;
}
$a = $runRequest();
print_r($a); //contains array of endpoint like in the sample above
【问题讨论】: