Home > Backend Development > PHP Tutorial > How to Sort an Associative Array by Numeric Value and Key Alphabetically?

How to Sort an Associative Array by Numeric Value and Key Alphabetically?

Patricia Arquette
Release: 2024-11-11 07:48:03
Original
975 people have browsed it

How to Sort an Associative Array by Numeric Value and Key Alphabetically?

Sorting Arrays by Numeric Values and Keys

In programming, situations arise where we need to sort associative arrays by specific criteria. One such scenario is sorting an array by numeric values and then by keys.

Suppose we have an array containing string keys and numeric values representing tag occurrences:

$arrTags = [
    'mango' => 2,
    'orange' => 4,
    'apple' => 2,
    'banana' => 3
];
Copy after login

Our goal is to display the tags in a list with the highest occurrence first, and in case of equal occurrences, sort the tag names alphabetically. This would result in:

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

While the arsort() function can initially sort the values, it will fail to maintain the alphabetical order of keys when multiple values are equal.

As suggested by Scott Saunders, we can utilize the array_keys() and array_values() functions to overcome this limitation:

array_multisort(array_values($arrTags), SORT_DESC, array_keys($arrTags), SORT_ASC, $arrTags);
Copy after login

This combination of functions allows us to directly manipulate the array's keys and values, ultimately achieving the desired sorting behavior. By sorting the values in descending order and then sorting the keys in ascending order, we obtain our desired output.

The above is the detailed content of How to Sort an Associative Array by Numeric Value and Key Alphabetically?. 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