Home > Backend Development > PHP Tutorial > How to sort an array based on a specific key-value pair using PHP, preserving the original key names?

How to sort an array based on a specific key-value pair using PHP, preserving the original key names?

PHPz
Release: 2024-04-30 16:30:02
Original
562 people have browsed it

Use the PHP uasort function and provide a comparison function to sort the array according to the specific key values ​​in the array while retaining the original key names. The specific steps are as follows: define a comparison function that accepts two key-value pairs as parameters and returns an integer; call the uasort function and pass in the array to be sorted and the comparison function; the sorted array will retain the original key names.

如何使用 PHP 根据数组中某个具体键值对进行排序,保留原始键名?

#How to use PHP to sort according to a specific key-value pair in an array, retaining the original key name?

In PHP, use the uasort function to sort according to a specific key-value pair in the array while retaining the original key name. Here is its syntax:

uasort(array $array, callable $value_compare_func)
Copy after login

Where:

  • array The array to sort
  • value_compare_func A comparison Function, which will be used to compare two key-value pairs in the array

The comparison function should accept two parameters (the key-value pairs of the two elements in the array) and return an integer:

  • -1 If the first key-value pair should be sorted before the second key-value pair
  • 0 If both key-value pairs For equality
  • 1 If the first key-value pair should be ranked after the second key-value pair

Practical case

Suppose we have an array named $data which contains student information and their grades:

$data = [
    'John Doe' => 85,
    'Jane Smith' => 90,
    'Bob Jones' => 75
];
Copy after login

We can use the following code to sort the array based on grades, While retaining the original key names:

uasort($data, function($a, $b) {
    return $a - $b;
});
Copy after login

The sorted array will look like this:

print_r($data);
// 输出:
// Array
// (
//     [Jane Smith] => 90
//     [John Doe] => 85
//     [Bob Jones] => 75
// )
Copy after login

The above is the detailed content of How to sort an array based on a specific key-value pair using PHP, preserving the original key names?. 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