Home >Backend Development >PHP Tutorial >How to sort an array using a custom comparison function in PHP and preserve key names?

How to sort an array using a custom comparison function in PHP and preserve key names?

WBOY
WBOYOriginal
2024-05-04 11:51:01558browse

Using custom comparison functions in PHP can sort arrays and preserve key names. In order to do this, you can use the usort() function, which takes an array and a callback function as parameters. The callback function receives two array elements and returns an integer (-1, 0, or 1) to indicate the sort order.

PHP 中如何使用自定义比较函数对数组进行排序,并保留键名?

Use a custom comparison function to sort the array in PHP and retain the key names

Using a custom comparison function to sort the array is part of the array operation common operations. In PHP, this can be easily accomplished using the usort() function.

Syntax

usort(array, callable)
  • array: The array to be sorted.
  • callable: Callback function used to compare array elements. It must accept two arguments (two array elements) and return an integer (-1, 0, or 1).

Practical Case

The following example shows how to use a custom comparison function to sort the key names in an array while retaining the key names:

<?php

// 待排序的数组
$arr = [
    'a' => 10,
    'c' => 5,
    'b' => 20,
];

// 自定义比较函数
$compare = function ($a, $b) {
    return strcmp($a['key'], $b['key']);
};

usort($arr, $compare);

// 输出排序后的数组
print_r($arr);

In this In the example, the compare function takes two key names ($a['key'] and $b['key']) as parameters and uses strcmp() function compares them. strcmp() The function returns -1, 0, or 1, indicating whether the first string is less than, equal to, or greater than the second string.

When the usort() function is called, it applies the specified comparison function to each element in the $arr array. If the compare function returns -1, the first element is sorted before the second element; if it returns 1, the reverse is true; if it returns 0, the order of the elements remains unchanged.

The final output is:

Array
(
    [a] => 10
    [b] => 20
    [c] => 5
)

The array is sorted from small to large according to the key names, while retaining the key names.

The above is the detailed content of How to sort an array using a custom comparison function in PHP and preserve 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