Home > Backend Development > PHP Tutorial > How to Sort an Associative Array by Numeric Values and Keys in Descending Order?

How to Sort an Associative Array by Numeric Values and Keys in Descending Order?

Barbara Streisand
Release: 2024-11-12 06:22:01
Original
797 people have browsed it

How to Sort an Associative Array by Numeric Values and Keys in Descending Order?

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

should be output as:

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

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

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!

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