问题
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?
回答1:
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)
}
来源:https://stackoverflow.com/questions/24205222/sort-associative-array-according-to-value-without-deleting-keys