简体   繁体   English

在 PHP 中按键长度(值中的键长度)对数组进行降序排序

[英]Sort an array in descending order by key length (key length in value) in PHP

My question is an extension/variation on this already well-answered question :我的问题是对这个已经得到很好回答的问题的扩展/变体:

There is an array with binary-looking keys:有一个带有二进制键的数组:

    codeWords = [
        '000111' => [6, 1, 0, 't'],
        '1110' => [4, 6, 0, 't'],
        '10011' => [5, 8, 0, 't'],
        '001000' => [6, 12, 0, 't'],
        '00110101' => [8, 0, 0, 't'],
        '010' => [3, 1, 1, 't'],
        '10' => [2, 3, 1, 't'],
        '011' => [3, 4, 1, 't'],
        '0010' => [4, 6, 1, 't'],
        '00011' => [5, 7, 1, 't'],
        '000101' => [6, 8, 1, 't'],
    ];

I need this array ordered like this:我需要这样排列的数组:

    $codeWords = [
        '00110101' => [8, 0, 0, 't'],
        '001000' => [6, 12, 0, 't'],
        '000111' => [6, 1, 0, 't'],
        '000101' => [6, 8, 1, 't'],
        '10011' => [5, 8, 0, 't'],
        '00011' => [5, 7, 1, 't'],
        '1110' => [4, 6, 0, 't'],
        '0010' => [4, 6, 1, 't'],
        '011' => [3, 4, 1, 't'],
        '010' => [3, 1, 1, 't'],
        '10' => [2, 3, 1, 't'],
    ];

This solution is working fine:此解决方案运行良好:

    uksort($codeWords, function($a, $b) {
        return strlen($a) < strlen($b);
    });

but...但...

...key length is already stored in value[0] . ...密钥长度已存储在value[0]中。 Therefore, strlen() does not have to be used in the comparison function.因此,在比较 function 时不必使用strlen()

I have tried to adapt some of the solutions given in the linked question accordingly with using value[0] - but do not come to the desired result.我已经尝试使用value[0]相应地调整链接问题中给出的一些解决方案 - 但没有达到预期的结果。

Can someone get me on the right track?有人可以让我走上正确的轨道吗?

The uksort function specifically uses array keys, and thus your code return $a[0] < $b[0]; uksort function 专门使用数组键,因此您的代码return $a[0] < $b[0]; compares only first symbols of your 0010101 keys.仅比较0010101键的第一个符号。

You need uasort .你需要uasort

    uasort($codeWords, function($a, $b) {
        return $b[0] - $a[0];
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM