PHP-按密钥长度对哈希数组进行排序

问题描述:

我找到了一些按值而不是键排序的答案.

I've found a few answers to sorting by value, but not key.

我想做的是反向排序,所以:

What I'd like to do is a reverse sort, so with:

    $nametocode['reallylongname']='12';
    $nametocode['shortname']='10';
    $nametocode['mediumname']='11';

我希望他们按照这个顺序

I'd like them to be in this order

  1. reallylongname
  2. 中等名称
  3. 简称

mediumname短名称

mediumname shortname

非常感谢

使用 array_multisort :

$keys = array_map('strlen', array_keys($arr));
array_multisort($keys, SORT_DESC, $arr);

此处$keys$arr的键的长度的数组.该数组按降序排序,然后用于使用array_multisort$arr的值进行排序.

Here $keys is an array of the lengths of the keys of $arr. That array is sorted in descending order and then used to sort the values of $arr using array_multisort.