根据值对关联数组进行排序,而无需删除键 [英] Sort associative array according to value without deleting keys

查看:108
本文介绍了根据值对关联数组进行排序,而无需删除键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要根据其值排序的数组.但是,当我使用rsort时,它将删除所有键.我尝试翻转数组,然后使用krsort,但是随后它删除了一些具有相同键的键/值对.

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
)

如何实现?

推荐答案

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

You can use arsort(). From the manual:

arsort —以相反的顺序对数组进行排序并保持索引关联

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

示例:

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

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

输出:

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

这篇关于根据值对关联数组进行排序,而无需删除键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆