Sorting Associative Arrays by Numeric Values and Keys
Given an associative array with string keys and numeric values, you want to sort the array by descending numeric values and then alphabetically by tag names. For example, the input array:
$arrTags = [ 'mango' => 2, 'orange' => 4, 'apple' => 2, 'banana' => 3 ];
should be output as:
orange (4) banana (3) apple (2) mango (2)
Solution:
One possible approach is to use usort(). However, you need a custom comparison function that sorts by numeric values first and then by keys. This can be done by sorting in two steps: first, sort by descending numeric values, and then sort by ascending key values.
To simplify the code, you can use the array_values() and array_keys() functions to extract the values and keys into separate arrays. Then, use array_multisort() to perform multiple sorts on multiple arrays. The following code will produce the desired output:
array_multisort(array_values($arrTags), SORT_DESC, array_keys($arrTags), SORT_ASC, $arrTags);
The above is the detailed content of How to Sort an Associative Array by Numeric Values and Keys in Descending Order?. For more information, please follow other related articles on the PHP Chinese website!