Home > Backend Development > PHP Tutorial > How to Sort an Associative Array by Numeric Value and Key in Descending and Ascending Order Respectively?

How to Sort an Associative Array by Numeric Value and Key in Descending and Ascending Order Respectively?

Susan Sarandon
Release: 2024-11-11 10:01:03
Original
327 people have browsed it

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
];
Copy after login

The desired output for this array is a sorted list:

orange (4)  
banana (3) 
apple (2) 
mango (2)
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template