Home > Backend Development > PHP Tutorial > PHP: Sort array by value, keep keys and reverse order

PHP: Sort array by value, keep keys and reverse order

WBOY
Release: 2024-05-04 15:48:01
Original
1180 people have browsed it

To sort an array by value and reverse the order in PHP, you can use the following steps: Sort by value in ascending order: Use the asort($array) function. Sort by value in descending order: use the arsort($array) function.

PHP: Sort array by value, keep keys and reverse order

PHP: Sort array by value, retain keys and reverse order

Question

It is often necessary to sort an array based on its value while retaining the original key association. In addition, sometimes it is necessary to reverse the sorted results. This article explains how to implement these tasks in PHP.

Code

1. Sort the array by value

$array = ['apple' => 1, 'banana' => 3, 'cherry' => 2];
asort($array); // 按值升序排序,保留键
Copy after login

2. Sort the array by value

arsort($array); // 按值降序排序,保留键
Copy after login

Practical case

Sort products by user ratings

The following code snippet shows how to sort products based on user ratings Practical example of sorting an array of products by ratings and in reverse order:

$products = [
    ['name' => 'Product 1', 'rating' => 4.5],
    ['name' => 'Product 2', 'rating' => 3.8],
    ['name' => 'Product 3', 'rating' => 4.2],
];

usort($products, function($a, $b) {
    return $b['rating'] - $a['rating']; // 按评级降序排序
});
Copy after login

After executing this code snippet, the $products array will contain products sorted by user ratings from high to low, while retaining the original product name keys.

The above is the detailed content of PHP: Sort array by value, keep keys and reverse order. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template