Skip to content
Advertisement

PHP array multiple sort – by value then by key?

I have an array of string keys with numeric values for use in a list of tags with the number of occurances of each tag, thus:

$arrTags['mango'] = 2; 
$arrTags['orange'] = 4; 
$arrTags['apple'] = 2; 
$arrTags['banana'] = 3;

this is so i can display the tag list in descending occurance order thus:

orange (4)  
banana (3) 
mango (2) 
apple (2)

i can use arsort to reverse sort by the value which is brilliant but i also want any tags that have the same numeric value to be sorted alphabetically, so the final result can be:

orange (4)  
banana (3) 
apple (2) 
mango (2)

is there a way i can do this? i’m guessing that usort may be the way to go but i look at the examples on php.net and my eyes glaze over! many thanks!!!

Advertisement

Answer

Have a look at examples #3: http://php.net/manual/en/function.array-multisort.php

You’ll need to create two arrays to use as indexes; one made up of the original array’s keys and the other of the original array’s values.

Then use multisort to sort by text values (keys of the original array) and then by the numeric values (values of the original array).

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement