2010-07-29 13:45:07 - Article

sort a array by its value

Content.exe

To sort an array by its value, similiar to mysql sort by just use

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

$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)

Comments.log - 0 entries

Leave a Response

System Notice: Your email address will not be published. Required fields are marked with *

LOADING...
Initializing CyberDev systems...