<?php
$array = [
"b" => 2,
"a" => 1,
"c" => 3,
];
krsort($array);
print_r($array);
?>
After running, the output result:
Array
(
[c] => 3
[b] => 2
[a] => 1
)
Here, the key names are sorted from large to small by letter, which meets expectations.
When krsort() sorts by key names, the key names will be automatically treated as strings or integers. If the key names of the array are mixed, the sorting result may not be as expected.
For example:
<?php
$array = [
2 => 'two',
"10" => 'ten',
1 => 'one',
];
krsort($array);
print_r($array);
?>
At this time, the key name 10 is a string but is actually a numeric key, which will be converted into an integer processing, which may cause the sorting order to be inconsistent with the expected one.
krsort() only sorts the first layer key names of the array. If it is a multidimensional array, the internal subarray will not be sorted.
<?php
$array = [
"first" => ["b" => 2, "a" => 1],
"second" => ["d" => 4, "c" => 3],
];
krsort($array);
print_r($array);
?>
Here we will only sort the first-level key names, first and second , and the internal key names of b, a, d, and c will not change.
krsort() only supports array parameters. If a non-array (such as an object or a string) is passed in, the function will not work and may even report an error.
Check if the variable is an array
Use the is_array() function to verify to avoid misuse.
if (!is_array($array)) {
echo "The variable passed in is not an array,Unable to sort";
}
Check if the key name type is consistent
Check whether the key names are all strings or integers to avoid mixing and causing sorting exceptions.
foreach ($array as $key => $value) {
var_dump($key, gettype($key));
}
Confirm whether the expected hierarchy is sorted
For multi-dimensional arrays, it is necessary to clarify which layer you need to sort.
Several solutions are given to the above problems:
If the key names are mixed, the key name type is unified first:
<?php
$newArray = [];
foreach ($array as $key => $value) {
$newArray[(string)$key] = $value;
}
krsort($newArray);
print_r($newArray);
?>
This avoids confusion of numeric strings.
If you need to sort the subarray key names as well, use the recursive method:
<?php
function recursive_krsort(&$array) {
if (!is_array($array)) return;
krsort($array);
foreach ($array as &$value) {
if (is_array($value)) {
recursive_krsort($value);
}
}
}
recursive_krsort($array);
print_r($array);
?>
<?php
if (is_array($array)) {
krsort($array);
} else {
echo "Variables are not arrays,Unable to sort。";
}
?>
For more detailed instructions and examples about PHP krsort() , you can access the official documentation:
<code> https://gitbox.net/manual/en/function.krsort.php </code>