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!!!
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With