I have a MySQL table with the following attributes: store_name lat lon
I have 1500 records.
I need to find the closest store to the user (based on IP).
I have figured the IP translation part using a 3rd party API. I know how to calculate the distance between 2 coordinates. However, I don't know how to return the store name that is the closest.
My function to calculate distance
function distance($lat1, $lon1, $lat2, $lon2)
{
$minus = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1))*cos(deg2rad($lat2)) * cos(deg2rad($minus));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
return $miles;
}
I can find the distance between user and each store.
Note: $lat1 and $lat1 are obtained by a 3rd party API service.
$store = mysql_query("SELECT * FROM store") or die(mysql_error());
while($row=mysql_fetch_assoc($store))
{
$lat2 = $row["lat"];
$lon2 = $row["lon"];
$distance = distance($lat1, $lon1, $lat2,$lon2);
}
How do I calculate run the distance function and store the distance value in an array and then sort the distances to find the nearest store? Is this the correct methodology? And how do I proceed with the array code? I have no experience with arrays in PHP.
Thank you.