sort a array by its value
To sort an array by its value, similiar to mysql sort by just use
1 | usort($array, create_function('$a, $b, $sortBy="distance"', 'return strnatcmp($a[$sortBy], $b[$sortBy]);')); |
$array stores the array
$sortBy set the key to sort by
i.e
1 2 3 4 5 6 7 | $array = array ( 1=>array('name'=>'me','location'=>'somewhere','distance'=>'200'), 2=>array('name'=>'you','location'=>'somewhere','distance'=>'2') ); usort($array, create_function('$a, $b, $sortBy="distance"', 'return strnatcmp($a[$sortBy], $b[$sortBy]);')); print_r($array); |
will result in the array being re-ordered with location 2 now being in location 1 (preserving the keys)
4,897 views
This entry was posted on Thursday, July 29th, 2010 at 1:45 pm and is filed under Programming. You can follow any responses to this entry through the RSS 2.0 feed.