PHP - sort hash array by key length

后端 未结 11 1416
星月不相逢
星月不相逢 2021-01-04 08:40

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         


        
11条回答
  •  猫巷女王i
    2021-01-04 09:08

    Another solution using array_multisort:

    $keys = array_map('strlen', array_keys($arr));
    array_multisort($keys, SORT_DESC, $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.

提交回复
热议问题