根据值对关联数组进行排序而不删除键

时间:2014-06-13 12:24:27

标签: php arrays sorting usort

我有一个数组,我想根据它的值进行排序。但是当我使用rsort时,它会删除所有密钥。我尝试翻转数组,然后使用krsort,但随后删除了一些具有相同键的键/值对。

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
)

如何实现?

1 个答案:

答案 0 :(得分:3)

您可以使用arsort()。从手册:

  

arsort - 按相反顺序对数组进行排序并维护索引关联

示例:

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

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

输出:

array(3) {
  '534d5a4b8ead0e5b73294d72' =>
  int(45)
  '533ee8bc8ead0ec5138b4567' =>
  int(32)
  '533ae5a78ead0e8e118b4567' =>
  int(1)
}