php - Sorting nested arrays via an Element in each Sub Array -
assuming have coming json request looks --
$data = array('0'=> array('name' => 'dr. smith', 'address' => '3002 fake ave.', 'lat' => '34.711158', 'lng' => '-137.803578', 'phone' => '714.939.1324'), '1' => array('name' => 'dr. paul', 'address' => '801 fake st.', 'lat' => '31.749917', 'lng' => '-137.834388'));
how order 1 of elements? if wanted sort whole array of arrays lat
element? , put in $data
element, can keep working it.
i've read stuff on php usort
, sorting sub-array element, when try work code examples aren't working.
the callback function usort receive 2 of array entries (which arrays in themselves) , must answer whether $a comes before or after $b.
for example function receive
$a = array('lat' => 45, 'name' => 'mickey mouse', ...) $b = array('lat' => 47, ...)
so if want sort lat element, use,
function sort_by_lat($a, $b) { return $a['lat'] - $b['lat']; // or b - sort other way } usort($array, "sort_by_lat");
a problem might have way, if sorted longitude, might consider -1 less +1, , -179 less +180. might or might not expect. in case need use if(), and/or introduce conversion.
to sort name, can do
if ($a['field'] > $b['field']) return 1; if ($a['field'] == $b['field']) return 0; return -1;
(again invert +1 , -1 sorted other way).
Comments
Post a Comment