Home >Backend Development >PHP Tutorial >How Can I Sort an Associative Array by Numeric Values and Then by Keys in PHP?

How Can I Sort an Associative Array by Numeric Values and Then by Keys in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-10 03:35:021006browse

How Can I Sort an Associative Array by Numeric Values and Then by Keys in PHP?

Sort an Associative Array by Numeric Values and Then by Keys

In PHP, you may encounter scenarios where you need to sort a flat, associative array based on numeric values and then by keys. This can be a challenging task, especially if you're not familiar with the appropriate techniques.

One approach is to use usort() to compare the values and keys simultaneously. However, this can be a tedious and complex solution.

A simpler and more efficient solution is to utilize the array_values() and array_keys() functions in conjunction with array_multisort(). This technique allows you to achieve the desired sorting in a single line of code:

array_multisort(array_values($arrTags), SORT_DESC, array_keys($arrTags), SORT_ASC, $arrTags);

This code isolates the numeric values and keys into separate arrays, sorts them descending and ascending, respectively, and then merges the results back into the original $arrTags array.

The resulting $arrTags will be sorted in descending order by numeric values and then by ascending order by keys, providing the desired format:

orange (4)  
banana (3) 
apple (2) 
mango (2)

The above is the detailed content of How Can I Sort an Associative Array by Numeric Values and Then by Keys in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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