Home >Backend Development >PHP Tutorial >PHP: Sort array by value, keep keys and reverse order
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, 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); // 按值升序排序,保留键
2. Sort the array by value
arsort($array); // 按值降序排序,保留键
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']; // 按评级降序排序 });
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!