PHP - sort hash array by key length

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

提交回复
热议问题