You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中返回值为逗号时重复调用函数10次的实现问题

解决getCoordinates返回","时的重试问题

Hey there, let's fix up your retry logic for the getCoordinates function! I noticed a couple of small issues in your current code that might trip it up, plus we can tweak it to be more reliable.

First, let's spot the bugs in your existing code:

  • You used the comparison operator == when initializing $i — that should be the assignment operator =, otherwise $i never gets set to 0 and your loop might not run correctly.
  • The condition $i <= 10 would let you retry 11 times (from i=0 to i=10). If you want a strict maximum of 10 retries after the first call, switch to $i < 10.

Here's the corrected, optimized code:

// First attempt to get coordinates
$coordinates1 = getCoordinates($placeadress); 
// Initialize retry counter properly with =
$i = 0; 

// Retry up to 10 times if we only get ","
while ($coordinates1 == ',' && $i < 10) { 
    // Optional: Add a small delay to avoid hitting API rate limits
    sleep(1);
    $coordinates1 = getCoordinates($placeadress); 
    $i++; 
}

A few notes to make this more robust:

  • The sleep(1) is optional but highly recommended if getCoordinates is calling an external API (like a geocoding service). It prevents you from flooding the API with rapid requests, which could get you blocked or throttled.
  • If you want to cap the total number of calls at 10 (instead of 1 initial + 10 retries), adjust the counter start and condition to:
    $i = 1;
    while ($coordinates1 == ',' && $i < 10) {
        // ... retry logic
        $i++;
    }
    

Just a quick check on your getCoordinates function too: the str_replace(" ", "+", $address) is a solid first step for URL-encoding the address, which is exactly what you need if you're passing it to a geocoding API endpoint.

内容的提问来源于stack exchange,提问作者DigiNet Events

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:30:58