Home  >  Article  >  Backend Development  >  PHP How to sort an array by value while retaining the original key names?

PHP How to sort an array by value while retaining the original key names?

WBOY
WBOYOriginal
2024-05-04 08:06:02724browse

PHP provides two ways to sort associative arrays by value: Use the asort() function: sort the values ​​from small to large while retaining the original key names. Using the usort() function and closures: Sort values ​​by a custom comparison function while preserving the original key names.

PHP 如何按值对数组进行排序,同时保留原始键名?

Using the asort() function

PHP’s asort() function Associative arrays can be sorted by value while preserving the original key names. It accepts an associative array as argument and sorts the values ​​from smallest to largest.

<?php
$arr = [
    "apple" => 5,
    "banana" => 3,
    "orange" => 2,
    "grape" => 4,
];

asort($arr);

print_r($arr);
?>

Output:

Array
(
    [orange] => 2
    [banana] => 3
    [grape] => 4
    [apple] => 5
)

As you can see, the values ​​of the array have been sorted from small to large, but the key names remain unchanged.

Using usort() Functions and closures

Another way is to use usort() Functions and closures Bag. usort() Accepts a callback function as a parameter, which is used to compare elements in the array. A closure is an anonymous function that can be used as a callback.

<?php
$arr = [
    "apple" => 5,
    "banana" => 3,
    "orange" => 2,
    "grape" => 4,
];

usort($arr, function ($a, $b) {
    return $a[1] - $b[1];
});

print_r($arr);
?>

Output:

Array
(
    [orange] => 2
    [banana] => 3
    [grape] => 4
    [apple] => 5
)

In this case, the closure compares the value of each element ($a[1] and $b[ 1]), and returns -1, 0, or 1, depending on which value is greater.

The above is the detailed content of PHP How to sort an array by value while retaining the original key names?. 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