1

I have an array which i want to sort on the basis of its value. But when i'm using rsort, it deletes all the keys. I tried to flip array and then used krsort, but then it removes some key/values pairs which have the same key.

Array
(
    [533ae5a78ead0e8e118b4567] => 1
    [534d5a4b8ead0e5b73294d72] => 45
    [533ee8bc8ead0ec5138b4567] => 32
    [535f42748ead0ef72ec72731] => 1
    [537cc7128ead0e683071f3c0] => 2
    [5388795b8ead0ea32f208680] => 3
    [538c4f1a8ead0e75472f05b0] => 6
    [538963758ead0e6759208680] => 5
    [538961a58ead0e0459208680] => 3
    [5389616e8ead0ecc58208680] => 3
    [538962c68ead0eb6582098d8] => 2
    [538964c78ead0ec159208680] => 1
    [53887efc8ead0e2b35208680] => 1
    [538964678ead0ea659208680] => 3
)

How to achieve that?

2

1 Answer 1

3

You can use arsort(). From the manual:

arsort — Sort an array in reverse order and maintain index association

Example:

$a = array(
    '533ae5a78ead0e8e118b4567' => 1,
    '534d5a4b8ead0e5b73294d72' => 45, 
    '533ee8bc8ead0ec5138b4567' => 32
);

arsort($a);
var_dump($a);

Output:

array(3) {
  '534d5a4b8ead0e5b73294d72' =>
  int(45)
  '533ee8bc8ead0ec5138b4567' =>
  int(32)
  '533ae5a78ead0e8e118b4567' =>
  int(1)
}
2
  • 1
    WTH. I think lot of coding in a single day is injurious to health. :D . Don't know how i forgot that. Thanks though.
    – Kanav
    Jun 13, 2014 at 12:34
  • 1
    Ok, save the file and shutdown the computer for a while! ;)
    – hek2mgl
    Jun 13, 2014 at 12:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.