简体   繁体   English

排序多维数组而不会丢失键值

[英]Sorting multidimensional array without losing key values

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标识符吗?

I think what you're looking for is asort() instead of usort() . 我认为您正在寻找的是asort()而不是usort() That'll maintain the key indexes and just sort by values in ascending order. 这将维护键索引,并仅按值升序排序。

For the sorting you want asort() will do the trick. 对于排序,您希望asort()可以解决问题。 - --

asort($tallyArray);

Sort an array and maintain index association 对数组进行排序并维护索引关联

asort() asort()

DEMO 演示

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

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