PHP - API 调用 foreach

PHP - API call foreach

我在尝试理解为什么我的代码不起作用时遇到了一些困难。它应该像这样工作:

  1. 我参观了路线/postman-test-route
  2. 它使用一些 headers 和参数
  3. https://pro-sitemaps.com/api/ 进行 API 调用
  4. 每个 API 结果显示最多 20 个条目
  5. 显示结果时,我会迭代结果并计算条目数,因此如果 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 中处理的条目总数。这将使我们能够不断获得新物品而不是旧物品。

$shouldProcess 是一个 bool,它将指示我们是否应该继续尝试从 API.

中获取新条目

$items 是一个数组,它将保存 API.

中的所有条目

$processedThisLoop 包含我们在此循环中处理的条目数量,即对 API 的请求是否有任何条目要处理?如果没有,则将 $shouldProcess 设置为 false,这将停止 while 循环。