user1355300
user1355300

Reputation: 4987

Sort an array from high to low

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

Answers (4)

Legionar
Legionar

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

Ram Sharma
Ram Sharma

Reputation: 8819

change

$array = rsort($array);
print_r($array);  

to

rsort($array);
print_r($array);  

Upvotes: 1

Amal Murali
Amal Murali

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
        )

)

Working demo

Upvotes: 7

sergio0983
sergio0983

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

Related Questions