PHP - sort hash array by key length

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

    You can use a user defined key sort function as a callback for uksort:

    function cmp($a, $b)
    {
        if (strlen($a) == strlen($b))
            return 0;
        if (strlen($a) > strlen($b))
            return 1;
        return -1;
    }
    
    uksort($nametocode, "cmp");
    
    foreach ($nametocode as $key => $value) {
        echo "$key: $value\n";
    }
    

    Quick note - to reverse the sort simply switch "1" and "-1".

    0 讨论(0)
  • 2021-01-04 09:09

    I have benchmarked some of sorting algorithms since performance is important for my project - here's what I've found (averaged result ran 1000x, sorted field had cca 300 elements with key size 3-50 chars):

    • 2.01 sec ... uksort with anonymous create_function (by cojam)
    • 0.28 sec ... array_multisort (by Gumbo)
    • 2.69 sec ... uksort with non-anonymous function (by Colin Herbert) - surprise for me,
    • 0.15 sec ... simple foreach + arsort

    Sometime simple foreach still wins. Using dynamic PHP features has some performance penalty, obviously.

    0 讨论(0)
  • 2021-01-04 09:12

    In PHP7+ you can use uksort() with spaceship operator and anonymous function like this:

    uksort($array, function($a, $b) {
        return strlen($b) <=> strlen($a);
    });
    
    0 讨论(0)
  • 2021-01-04 09:12

    A simple problem requires a simple solution ;-)

    arsort($nametocode, SORT_NUMERIC);
    $result = array_keys($nametocode);
    
    0 讨论(0)
  • 2021-01-04 09:21

    Behold my powerful inline methodologies. Preserve global space for the generations to come!

    uksort($data, create_function('$a,$b', 'return strlen($a) < strlen($b);'));
    
    0 讨论(0)
提交回复
热议问题