在不丢失键值的情况下对多维数组进行排序

时间:2022-08-10 21:34:43

I have this array.

我有这个数组。

Array
(
    [Abdominal ascitis] => 11
    [Infection (not neutropenic)] => 25
    [Nausea/Vomiting] => 8
    [Pain] => 17
    [Abdominal pain] => 18
    [Bowel obstruction] => 5
    [Back pain] => 3
    [Bleeding] => 12
    [Brain mets] => 8
    [Cerebral event] => 11
    [Chemotherapy toxicity] => 3
    [Neutropenic Sepsis] => 24
    [Constipation] => 1
    [Diarrhoea] => 3
    [Disease progression] => 3
    [SVCO] => 2
    [Shortness of breath] => 17
    [Disease related] => 2
    [Chest pain ] => 6
    [DVT] => 2
    [Falls] => 14
    [Hypercalcaemia] => 6
    [Jaundice] => 3
    [MSCC] => 9
    [New diagnosis] => 2
    [Other] => 11
    [Pleural effusion] => 8
    [Surgery related] => 1
    [Urinary tract infection] => 3
    [AKI] => 3
    [Dysphagia] => 4
    [Pulmonary Emboli] => 1
    [Biliary sepsis] => 1
)

I want to sort it by value.

我想按价值排序。

I tried doing something like this which works 50%.

我尝试做这样的工作50%。

usort($tallyArray, function($a, $b) {
    return $a - $b;
});

But it throws away my $key identifier.

但它抛弃了我的$ key标识符。

Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 1
    [4] => 2
    [5] => 2
    [6] => 2
    [7] => 2
    [8] => 3
    [9] => 3
    [10] => 3
    [11] => 3
    [12] => 3
    [13] => 3
    [14] => 3
    [15] => 4
    [16] => 5
    [17] => 6
    [18] => 6
    [19] => 8
    [20] => 8
    [21] => 8
    [22] => 9
    [23] => 11
    [24] => 11
    [25] => 11
    [26] => 12
    [27] => 14
    [28] => 17
    [29] => 17
    [30] => 18
    [31] => 24
    [32] => 25
)

Any way to sort it and keep the $key identifier?

有什么办法对它进行排序并保留$ key标识符?

2 个解决方案

#1


I think what you're looking for is asort() instead of usort(). That'll maintain the key indexes and just sort by values in ascending order.

我认为你要找的是asort()而不是usort()。这将维护关键索引,并按升序排序。

#2


For the sorting you want asort() will do the trick. -

对于你想要的排序asort()会做的。 -

asort($tallyArray);

Sort an array and maintain index association

对数组进行排序并维护索引关联

asort()

DEMO

#1


I think what you're looking for is asort() instead of usort(). That'll maintain the key indexes and just sort by values in ascending order.

我认为你要找的是asort()而不是usort()。这将维护关键索引,并按升序排序。

#2


For the sorting you want asort() will do the trick. -

对于你想要的排序asort()会做的。 -

asort($tallyArray);

Sort an array and maintain index association

对数组进行排序并维护索引关联

asort()

DEMO