How can I sort an associative array by one of its values?
For example:
$arr = array(
'ted' => array( 'age' => 27 ),
'bob' => array( 'age' => 18 ),
'jay' => array( 'age' => 24 )
);
$arr = ???
foreach ($arr as $person)
echo $person['age'], ', ';
So that the output is:
18, 24, 27
This is an oversimplified example just to demonstrate my question.
I still require that $arr
is an associative array.
Since you're sorting on a value inside a sub array, there's not a built-in function that will do 100% of the work. I would do a user-defined sort with:
http://www.php.net/manual/en/function.uasort.php
Here's an example comparison function that returns its comparison based on this value in the nested array
http://www.php.net/manual/en/array.sorting.php
This particular case will involve using one of the sort methods that use a callback to sort
You're not just sorting an associative array, you're sorting an associative array of associative arrays ;)
A uasort call is what you're after
The
uasort()
function allows you to specify a callback function, which will be responsible of doing the comparison between two elements -- so, should do just well, if you implement the proper callback function.Here, you'd have to implement a callback function that will receive two arrays -- and compmare the
age
item :Using that function in the following portion of code :
You would get you this resulting array :
This is a classical example where PHP 5.3 anonymous functions come in handy:
The
$a['age'] - $b['age']
is a small trick. It works because the callback function is expected to return a value < 0 is$a
is smaller than$b
and a value > 0 if$a
is bigger than$b
.