Home  >  Article  >  Backend Development  >  Fast array sorting method that preserves key names in PHP

Fast array sorting method that preserves key names in PHP

PHPz
PHPzOriginal
2024-05-02 15:06:01937browse

Fast array sorting method in PHP that preserves key names: use the ksort() function to sort the keys. Use the uasort() function to sort using a user-defined comparison function. Practical example: To sort an array of user IDs and scores by score while preserving the user ID, you can use the uasort() function and a custom comparison function.

PHP 中保留键名的快速数组排序方法

Fast array sorting method in PHP that preserves key names

In PHP, array sorting usually scrambles key names. However, sometimes it is important to preserve the original key names. Listed below are several ways to quickly sort an array while preserving key names:

1. Use ksort()

ksort() The function sorts the keys in the array and retains the original key names.

$arr = ['apple' => 5, 'banana' => 1, 'cherry' => 3];
ksort($arr);
print_r($arr);

Output:

Array
(
    [apple] => 5
    [banana] => 1
    [cherry] => 3
)

2. Use uasort()

##uasort() function Sort an associative array using a user-defined comparison function while preserving key names.

function cmp($a, $b)
{
    return $a <=> $b;
}

$arr = ['apple' => 5, 'banana' => 1, 'cherry' => 3];
uasort($arr, "cmp");
print_r($arr);

Output:

Array
(
    [banana] => 1
    [cherry] => 3
    [apple] => 5
)

Practical case

Suppose you have an array of user IDs and corresponding scores. You need to sort the array while preserving the user ID.

$scores = [
    'user1' => 85,
    'user2' => 90,
    'user3' => 75,
];

// 使用 uasort() 排序数组
function cmp($a, $b)
{
    return $a[1] <=> $b[1];
}

uasort($scores, "cmp");

The sorted array is now in ascending order by score while preserving the user ID:

Array
(
    [user3] => 75
    [user1] => 85
    [user2] => 90
)

The above is the detailed content of Fast array sorting method that preserves key names in PHP. 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