Home >Backend Development >PHP Tutorial >How to sort multidimensional array in PHP while preserving key names?

How to sort multidimensional array in PHP while preserving key names?

WBOY
WBOYOriginal
2024-05-03 21:51:01675browse

Sort multi-dimensional arrays while retaining key names: 1. Use uksort() to sort according to key values, and provide a comparison function that returns 1, -1 or 0 to indicate the relative order of key values. 2. Use krsort() to sort key values ​​from high to low, accepting an array parameter.

如何在 PHP 中对多维数组进行排序,同时保留键名?

How to sort a multidimensional array in PHP while preserving key names

Sometimes, you may need to sort a multidimensional array Sort while preserving their key names. For this purpose, PHP provides the uksort() and krsort() functions.

uksort

uksort() The function sorts an array based on the value of the array key. It accepts two parameters: an array containing the array to be sorted and a comparison function. The comparison function should return one of the following values:

  • 1 if the first element of the array should come before the second element
  • -1 if the first element of the array Should be
  • 0 after the second element if the first element of the array is equal to the second element
<?php

$cars = [
    "Mercedes" => "Germany",
    "BMW" => "Germany",
    "Toyota" => "Japan",
    "Honda" => "Japan"
];

uksort($cars, function($a, $b) {
    return strcmp($a, $b);
});

foreach ($cars as $key => $value) {
    echo "$key: $value\n";
}

?>

Output:

BMW: Germany
Honda: Japan
Mercedes: Germany
Toyota: Japan

krsort

krsort() The function sorts the array and sorts the key values ​​from high to low. It accepts one parameter, the array to sort.

<?php

$cars = [
    "Mercedes" => "Germany",
    "BMW" => "Germany",
    "Toyota" => "Japan",
    "Honda" => "Japan"
];

krsort($cars);

foreach ($cars as $key => $value) {
    echo "$key: $value\n";
}

?>

Output:

Toyota: Japan
Honda: Japan
Mercedes: Germany
BMW: Germany

The above is the detailed content of How to sort multidimensional array in PHP while 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