php - Search or sort multi dimensional array for closest lat and lon values
This may be difficult, I want to search the following multi-dimensional array based on closest match of lat and lon and return that sub-array.
For example I will have the following values already set:
Lat=50.6000, Lon=-74.15000
And I want to search the following, and return the array that is the closest match. Or sort the whole thing by closest to furthest.
Even better would be a way to just sort the list so the closest lat/lon are first down to the furthest away from. What I DON'T need is it sorted in descending order. I needs to be closest to the preset value above for example. Anyone have an idea?
Array
(
[0] => Array
(
[zipcode] => 28299
[latitude] => 36.234982
[longitude] => -81.913799
[cityname] => ACME
)
[1] => Array
(
[zipcode] => 17198
[latitude] => 50.735880
[longitude] => -74.143855
[cityname] => NEWLAND
)
[2] => Array
(
[zipcode] => 12203
[latitude] => 41.711931
[longitude] => -75.011806
[cityname] => ACE
)
)
Answer
Solution:
The Function here would do just that.... however, it returns a Multidimensional Array with with 2 major Elements
latitudes
andlongitudes
. The longitudes hold all the sorted Entries for the closest longitude values and the "latitudes" as well hold the sorted Entries for the closest latitude values. By default, the Function only returns the very Closest Match latitudinally and longitudinally. However, passing false as the last Parameter returns all sorted entries. The Code below illustrates it all:Answer
Solution:
Consider:
This uses the naive Euclidean distance formula, for more accurate calculations replace
distance
with one of the formulae listed here: https://en.wikipedia.org/wiki/Geographical_distanceAnswer
Solution:
I think I can combine the calculation and return the full array in order a little better if I do it like this. Will need to do some testing but it looks correct so far. @poiz