Reputation: 4987
In the following array, I want to change the key order from high to low (so for example the year 2014 data appears first).
print_r($array);
Output:
Array
(
[0] => Array
(
[year] => 2013
[name] => xx
)
[1] => Array
(
[year] => 2014
[name] => xx
)
)
I have tried using rsort
, but it returns only "1".
$array = rsort($array);
print_r($array); //1
var_dump($array); //bool(true).
Upvotes: 0
Views: 3549
Reputation: 7597
rsort
has return value of boolean, so just simple use it like this:
rsort($array);
And also, rsort
is sorting array values in reverse order, not array keys, check the documentation:
http://php.net/manual/en/function.rsort.php
So in reverse order simply just use krsort
- Sort an array by key in reverse order:
http://php.net/manual/en/function.krsort.php
So your code:
krsort($array);
Upvotes: 1
Reputation: 8819
change
$array = rsort($array);
print_r($array);
to
rsort($array);
print_r($array);
Upvotes: 1
Reputation: 76656
rsort()
will only work on single-dimensional arrays. You have a 2-dimensional array, so you will need to use a different function such as usort()
, which lets you use user-defined comparison function for sorting:
usort($data, function ($a, $b) {
return $a['year'] < $b['year'];
});
Output:
Array
(
[0] => Array
(
[year] => 2014
[name] => xx
)
[1] => Array
(
[year] => 2013
[name] => xx
)
)
Upvotes: 7
Reputation: 1278
usort($array, function($item1, $item2){
if ($item1->year > $item2->year ) return true;
else return false;
})
That´s if you wanted to order by year, if you want to order by keys uksort could be used instead
Upvotes: 0