Home > Article > Backend Development > How to Sort an Associative Array by Numeric Value and Key in Descending and Ascending Order Respectively?
Associative Array Sorting by Numeric Value and Key
This programming quandary involves an associative array with numeric values, specifically targeting the creation of a list where tags are sorted first by their descending occurrence counts, and subsequently by their ascending alphabetical order.
Problem Definition
Consider an exemplary array:
$arrTags = [ 'mango' => 2, 'orange' => 4, 'apple' => 2, 'banana' => 3 ];
The desired output for this array is a sorted list:
orange (4) banana (3) apple (2) mango (2)
The native PHP function arsort() falls short as it prioritizes mango before apple due to its alphabetical dominance.
Solution
Employing the array_keys() and array_values() functions, this problem can be tackled with greater efficiency. The following code exemplifies the solution:
array_multisort(array_values($arrTags), SORT_DESC, array_keys($arrTags), SORT_ASC, $arrTags);
This single line eliminates the need for a loop and accomplishes the necessary sorting by first extracting the values from the array into a sortable array using array_values(). Subsequently, the values are sorted in descending order using SORT_DESC. Concurrently, the corresponding keys are extracted using array_keys() and sorted in ascending order using SORT_ASC. The results are then re-combined into the original array, utilizing the provided $arrTags parameter.
The above is the detailed content of How to Sort an Associative Array by Numeric Value and Key in Descending and Ascending Order Respectively?. For more information, please follow other related articles on the PHP Chinese website!