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

Fast array sorting method that preserves key names in PHP

PHPz
Release: 2024-05-02 15:06:01
Original
987 people have browsed it

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);
Copy after login

Output:

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

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);
Copy after login

Output:

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

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");
Copy after login

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

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

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!

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