1

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

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

But it throws away my $key identifier.

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?

1
  • 4
    uasort() Commented May 12, 2015 at 12:33

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I used the arsort in the end to sort descending.
Note comment by @Rizier123 that we also have uasort() if you need sorting by user defined function.
0

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

asort($tallyArray);

Sort an array and maintain index association

asort()

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.