I have a table (user_zip_codes) with the users' zip_code, latitude and longitude. I have found a function here on stackoverflow that finds zip codes within a specific radius:
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;
}
It works perfectly. However, I would like the function to sort the array by distance (either by ASC og DESC). How should I adjust my query in order for this to happen?
Thanks in advance.
UPDATE: The word 'distance' might appear ambiguous (thanks to Jorge). I simply wish to sort the zip_codes by distance meant as the distance between two points.