Home >Backend Development >PHP Tutorial >How to sort multidimensional array in PHP while preserving key names?
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.
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:
<?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!