簡體   English   中英

PHP-API調用foreach

[英]PHP - API call foreach

我在理解為什么我的代碼不起作用時遇到一些困難。 它應該像這樣工作:

  1. 我訪問路線/postman-test-route
  2. 它使用一些標頭和參數對https://pro-sitemaps.com/api/進行API調用
  3. 每個API結果最多顯示20個條目
  4. 當顯示結果時,我將對結果進行迭代並計數條目,因此,如果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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM