PHP - sort hash array by key length

后端 未结 11 1235
星月不相逢
星月不相逢 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条回答
  •  北荒
    北荒 (楼主)
    2021-01-04 09:06

    To absolutely use uksort you can do like this:

    $nametocode['reallylongname']='12';
    $nametocode['name']='17';
    $nametocode['shortname']='10';
    $nametocode['mediumname']='11';
    
    uksort($nametocode, function($a, $b) {
       return strlen($a) - strlen($b);
    });
    
    array_reverse($nametocode, true);
    

    Output:

    Array
    (
       [reallylongname] => 12
       [mediumname] => 11
       [shortname] => 10
       [name] => 17
    )
    

    I have tested this code.

提交回复
热议问题