Home >Backend Development >PHP Tutorial >Sort array by value in PHP using own function, preserving key names

Sort array by value in PHP using own function, preserving key names

PHPz
PHPzOriginal
2024-05-05 08:36:021025browse

In PHP, the way to sort an array by value and preserve the key name using its own function is to get all the values ​​of the array and sort them. Get the key of the sorted value. Recombine the sorted values ​​with the keys of the original array.

在 PHP 中使用自有函数对数组按值进行排序,保留键名

Use your own function in PHP to sort the array by value, retaining the key name

Preface

In PHP, the sort() function can sort an array by value. However, this function destroys the key names. In order to preserve the key names, we need to use our own function.

Own functions

The following self-owned functions can sort the array by value while retaining the key name:

function sortByValue(array $array)
{
    $sortedValues = array_column($array, null);
    asort($sortedValues);

    $sortedKeys = array_keys($sortedValues);

    return array_combine($sortedKeys, $array);
}

Practical case

The following example demonstrates how to sort an array containing key names:

$array = [
    'apple' => 10,
    'banana' => 20,
    'orange' => 5
];

$sortedArray = sortByValue($array);

print_r($sortedArray);

The output is:

Array
(
    [orange] => 5
    [apple] => 10
    [banana] => 20
)

As you can see, the array is sorted by value in ascending order Sorted while preserving key names.

The above is the detailed content of Sort array by value in PHP using own function, preserving 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