PHP - sort hash array by key length

2020-07-03 03:51发布

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';
    $nametocode['shortname']='10';
    $nametocode['mediumname']='11';

I'd like them to be in this order

  1. reallylongname
  2. mediumname
  3. shortname

mediumname shortname

Many thanks

11条回答
走好不送
2楼-- · 2020-07-03 04:12

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));
});
查看更多
Anthone
3楼-- · 2020-07-03 04:15

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.

查看更多
Animai°情兽
4楼-- · 2020-07-03 04:18

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.

查看更多
▲ chillily
5楼-- · 2020-07-03 04:26

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

uksort($array, function($a, $b) {
    return strlen($b) <=> strlen($a);
});
查看更多
霸刀☆藐视天下
6楼-- · 2020-07-03 04:30

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".

查看更多
Luminary・发光体
7楼-- · 2020-07-03 04:31

A simple problem requires a simple solution ;-)

arsort($nametocode, SORT_NUMERIC);
$result = array_keys($nametocode);
查看更多
登录 后发表回答