Adrian Callaghan`s Blog

sort a array by its value

by Adrian on Jul.29, 2010, under Programming, Work

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)

VN:F [1.9.9_1125]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.9_1125]
Rating: +2 (from 2 votes)
2,330 views

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!