gpt4 book ai didi

PHP mysqli_fetch_array 选择最小值

转载 作者:行者123 更新时间:2023-11-29 07:01:23 25 4
gpt4 key购买 nike

大家好,感谢您的帮助。我想要做的是使用用户的纬度和经度,并将其与我保存在数据库中的纬度和经度以及相关城市名称进行比较。我现在的代码可以工作,但问题是 30 英里半径内可能有多于一行。看看我的代码,如果可以的话请帮助我。

<?php function distance($lat1, $lon1, $lat2, $lon2) {

$pi80 = M_PI / 180;
$lat1 *= $pi80;
$lon1 *= $pi80;
$lat2 *= $pi80;
$lon2 *= $pi80;

$r = 6372.797; // mean radius of Earth in km
$dlat = $lat2 - $lat1;
$dlon = $lon2 - $lon1;
$a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlon / 2) * sin($dlon / 2);
$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
$km = $r * $c;

//echo '<br/>'.$km;
$km = $km * 0.621371;
return $km;
}
include_once("dbconnect.php");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$grabCities = "SELECT * FROM cities";
$result = $mysqli->query($grabCities);
while($row = mysqli_fetch_array($result)){
$distance = distance(41.08866717,-81.4780426,$row['lat'],$row['longitude']);
if ($distance < 30){
echo $myCity = $row['City'] . "<BR>";
}

}
$mysqli->close();
?>

最佳答案

您可以使用 MYSQL 执行此操作,返回 1 个结果,这是您想要的结果。

sprintf('
SELECT
*,
(((acos(sin((%1$d*pi()/180)) *
sin((`lat`*pi()/180))+cos((%1$d*pi()/180)) *
cos((`lat`*pi()/180))*cos(((%2$d-`longitude`) *
pi()/180))))*180/pi())
) as distance
FROM `cities`
ORDER BY
distance ASC
LIMIT 1
',
$latitude,
$longitude
);

关于PHP mysqli_fetch_array 选择最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43335720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com