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$inever gets set to 0 and your loop might not run correctly. - The condition
$i <= 10would let you retry 11 times (fromi=0toi=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 ifgetCoordinatesis 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
相关产品推荐
相关产品推荐

