This question already has an answer here:
I looked quite a bit around (like here the array-sort-comparisons), and tried to figure out how to sort (or reverse) my multiple-elements array. But in vain.
I have three elements in my array, and want to sort the it by "year" ASC:
array(52) {
[0]=>
array(3) {
["id"]=>
string(2) "SI"
["year"]=>
string(4) "2012"
["value"]=>
string(7) "3711339"
}
[1]=>
array(3) {
["id"]=>
string(2) "SI"
["year"]=>
string(4) "2011"
["value"]=>
string(7) "3810626"
}
[2]=>
array(3) {
["id"]=>
string(2) "SI"
["year"]=>
string(4) "2010"
["value"]=>
string(7) "3714946"
}
How would that be possible? Somehow one needs to be able to specify which of the three elements is the "key" to be the basis of the sorting.
Thanks for any hints!
</div>
Use usort()
with a custom comparison function:
usort($arr, function (array $a, array $b) {
return $a['year'] - $b['year'];
});
PHP >= 5.5.0
array_multisort(array_column($array, 'year'), SORT_ASC, $array);
As you stated reversing will work for your example. you can do it fairly simple
$arr = array(2012, 2011, 2010);
$reversed_arr = array_reverse($arr);