PHP - sort hash array by key length

后端 未结 11 1236
星月不相逢
星月不相逢 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 08:58

    The code below sorts the PHP hash array by string length of the key, then by the case-sensitive key itself, both in ascending order, using a lambda function:

    uksort($yourArray, function ($a, $b) { 
       return (strlen($a) == strlen($b) ? strcmp($a, $b) : strlen($a) - strlen($b));
    });
    

    This code does the same in reverse order:

    uksort($yourArray, function ($b, $a) { 
       return (strlen($a) == strlen($b) ? strcmp($a, $b) : strlen($a) - strlen($b));
    });
    

提交回复
热议问题