Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!!!

like image 758
David Avatar asked Feb 17 '10 15:02

David


People also ask

How do you sort an array of associative arrays by the value of a given key in PHP?

The arsort() function sorts an associative array in descending order, according to the value. Tip: Use the asort() function to sort an associative array in ascending order, according to the value. Tip: Use the krsort() function to sort an associative array in descending order, according to the key.

Can you sort a multidimensional array?

array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions. Associative (string) keys will be maintained, but numeric keys will be re-indexed.

How do I sort a multidimensional array in PHP?

Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements.


1 Answers

As Scott Saunders hints in his comment to David's solution, you can use the array_keys() and array_values() functions to get rid of the loop. In fact, you can solve this in one line of code:

array_multisort(array_values($arrTags), SORT_DESC, array_keys($arrTags), SORT_ASC, $arrTags); 
like image 102
Jon Bernhardt Avatar answered Sep 18 '22 03:09

Jon Bernhardt