gpt4 book ai didi

php - 按距离对邮政编码邻近搜索进行排序(php/mysql)

转载 作者:行者123 更新时间:2023-11-29 01:40:36 24 4
gpt4 key购买 nike

我有一个表 (user_zip_codes),其中包含用户的邮政编码、纬度和经度。我在 stackoverflow 上找到了一个函数,可以找到特定半径内的邮政编码:

function zipcodeRadius($lat, $lon, $radius) {
global $mysqli;
$zipcodeList = array();
$radius = ($radius ? $radius : 20);
$sql = "SELECT userID,city,zip_code,country FROM user_zip_codes WHERE (3958*3.1415926*sqrt((lat-$lat)*(lat-$lat) + cos(lat/57.29578)*cos($lat/57.29578)*(lon-$lon)*(lon-$lon))/180) <= $radius GROUP BY zip_code";
if($stmt = $mysqli->prepare($sql)) {
$stmt->execute();
$stmt->bind_result($userID,$city,$zip_code,$country);
while($stmt->fetch()) {
$zipcodeList[] = array('userID'=>$userID,'city'=>$city,'zip_code'=>$zip_code,'country'=>$country);
}
}
return $zipcodeList;
}

它工作得很好。但是,我希望函数按距离对数组进行排序(按 ASC og DESC)。我应该如何调整我的查询才能做到这一点?

提前致谢。

更新:“距离”一词可能显得模棱两可(多亏了豪尔赫)。我只是想按距离对 zip_codes 进行排序,即两点之间的距离。

最佳答案

你可以使用类似的东西

$iDistance = 20;
$iRadius = 6371; // earth radius in km
$iRadius = 3958; // earth radius in miles
$fLat = x.y; // Your position latitude
$fLon = x.y; // Your position longitude

$strQuery = "
SELECT
*,
$iRadius * 2 * ASIN(SQRT(POWER(SIN(( $fLat - abs(pos.lat)) * pi() / 180 / 2),2) +
COS( $fLat * pi()/180) * COS(abs(pos.lat) * pi() / 180) * POWER(SIN(( $fLon - pos.lon) *
pi() / 180 / 2), 2) )) AS distance
FROM user_zip_codes pos
HAVING distance < $iDistance
ORDER BY distance";

在使用 SQL 之前,您必须在其中获取纬度/经度值。这对我有用

关于php - 按距离对邮政编码邻近搜索进行排序(php/mysql),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24735978/

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