<span><span><span class="hljs-meta"><?php</span></span><span>
</span><span><span class="hljs-comment">// This section is unrelated to the PHP code</span></span><span>
</span><span><span class="hljs-comment">// For example, here could be some initialization, declarations, or header outputs</span></span><span>
<p></span>echo "This part is unrelated to the main content\n";</p>
<p>?></p>
<p><hr></p>
<p><?php<br>
<span class="hljs-comment">/**</p>
<ul data-is-only-node="" data-is-last-node="">
<li>
<p>Title: How to Reverse Sort Keys in a Multidimensional Nested Array Using krsort in PHP?</p>
</li>
<li></li>
<li>
<p>krsort() is a commonly used array function in PHP. It sorts an array by <strong>keys</strong> in descending order (from high to low),</p>
</li>
<li>
<p>while maintaining the key-value relationship. This is particularly useful when working with data structures that require sorting by key in descending order.</p>
</li>
<li></li>
<li>
<h3>1. Basic Usage of krsort</h3>
</li>
<li>
$arr = [
"c" => 3,
"a" => 1,
"b" => 2
];
krsort($arr);
print_r($arr);
The result will be:
Array
(
[c] => 3
[b] => 2
[a] => 1
)
Suppose we have a multidimensional nested array:
$data = [
"group3" => [
"c" => 30,
"a" => 10,
"b" => 20
],
"group1" => [
"x" => 100,
"z" => 300,
"y" => 200
],
"group2" => [
"foo" => "bar",
"baz" => "qux"
]
];
If we reverse sort only the outermost layer’s keys:
krsort($data);
print_r($data);
The top-level keys will become group3, group2, group1.
If we want to reverse sort the keys not only for the outermost layer, but also for every sub-array, we need to write a recursive function:
function recursiveKrsort(array &$array) {
// First, reverse sort the keys for the current layer
krsort($array);
// Traverse each element, and if the value is an array, recursively call the function
foreach ($array as &$value) {
if (is_array($value)) {
recursiveKrsort($value);
}
}
}
// Example usage
recursiveKrsort($data);
print_r($data);
This way, all levels of the array will be reverse sorted by their keys.
Using krsort() allows easy reverse sorting of keys in one-dimensional arrays.
For multidimensional arrays, a recursive function can be used to handle each layer and achieve global key reversal.
This method is useful for scenarios where data needs to be sorted and displayed based on keys, such as configuration or grouped data.
*/
?>