[英]PHP - API call foreach
我在理解為什么我的代碼不起作用時遇到一些困難。 它應該像這樣工作:
/postman-test-route
https://pro-sitemaps.com/api/
進行API調用 entries == 20
,則進行另一個API調用,但將'from'
參數從0
更改為20
,然后是30
然后是40
然后是50
,直到條目少於20
。 但是看起來代碼只運行一次。 代碼如下:
$app->map(['GET', 'POST'],'/postman-test-route', function (Request $request, Response $response) {
function getPROsitemapsEntries($total_from)
{
$client = new Client([
'sink' => 'C:\Users\****\Desktop\temp.txt'
]);
$r = $client->request('POST', 'https://pro-sitemaps.com/api/', [
'form_params' => [
'api_key' => 'ps_UmTvDUda.***************',
'method' => 'site_history',
'site_id' => 3845****,
'from' => $total_from, // Fra enties ID, kan kjøre en foreach for hver 20 entries. Hold en counter på result, hvis mindre enn 20 så fortsett, ellers die.
]
]);
return $r;
}
$function_call = getPROsitemapsEntries(0);
$responseData = json_decode($function_call->getBody(), true);
$i = 0;
$items = array(); // ALL entries should be saved here.
foreach($responseData['result']['entries'] as $entries){
$items[] = $entries;
$i++;
}
// Here it should call the API again with 'from' = 20, then 30, then 40
if($i > 20){
getPROsitemapsEntries($i);
}else{
die;
}
因此,您可以看到以下代碼:
if($i > 20){
getPROsitemapsEntries($i);
}else{
die;
}
我想這將再次調用API,並且應該保存foreach新條目(而不是覆蓋)。 有人可以看到我在哪里做錯了嗎? 我很新
謝謝!
因此,您實際上是在再次調用API,只是沒有遍歷結果。
$shouldProcess = true;
$searchIndex = 0;
$items = [];
while ($shouldProcess) {
$processedThisLoop = 0;
$function_call = getPROsitemapsEntries($searchIndex);
$responseData = json_decode($function_call->getBody(), true);
foreach($responseData['result']['entries'] as $entries) {
$items[] = $entries;
$searchIndex++;
$processedThisLoop++;
}
if($processedThisLoop == 0) {
// Didn't find any so stop the loop
$shouldProcess = false;
}
}
var_dump($items);
在上面的代碼中,我們跟蹤在$searchIndex
處理的條目$searchIndex
。 這將使我們能夠繼續獲得新的物品,而不是舊的物品。
$shouldProcess
是一個bool
,它將指示我們是否應該繼續嘗試從API獲取新條目。
$items
是一個數組,其中包含API中的所有條目。
$processedThisLoop
包含我們在此循環中處理的條目數量,即對API的此請求是否有任何條目要處理? 如果沒有,則將$shouldProcess
設置$shouldProcess
false,這將停止while
循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.