PHP-按密钥长度对哈希数组进行排序 [英] PHP - sort hash array by key length
本文介绍了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
- reallylongname
- 中等名称
- 简称
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
.
这篇关于PHP-按密钥长度对哈希数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文