I have an array of this form:
Array
(
[first_level] => Array
(
[dir_3] => Array
(
[subdir_1] => Array
(
[file_2.mp4] => stdClass Object
(
[name] => file_2.mp4
)
[file_1.mp4] => stdClass Object
(
[name] => file_1.mp4
)
)
)
[dir_1] => Array
(
[subdir_2] => Array
(
[file_6.mp4] => stdClass Object
(
[name] => file_6.mp4
)
[file_9.mp4] => stdClass Object
(
[name] => file_9.mp4
)
[file_7.mp4] => stdClass Object
(
[name] => file_7.mp4
)
)
[subdir_1] => Array
(
[file_8] => stdClass Object
(
[name] => file_8.mp4
)
)
)
)
)
I need to order it like this:
Array
(
[first_level] => Array
(
[dir_1] => Array
(
[subdir_1] => Array
(
[file_8] => stdClass Object
(
[name] => file_8.mp4
)
)
[subdir_2] => Array
(
[file_6.mp4] => stdClass Object
(
[name] => file_6.mp4
)
[file_7.mp4] => stdClass Object
(
[name] => file_7.mp4
)
[file_9.mp4] => stdClass Object
(
[name] => file_9.mp4
)
)
)
[dir_3] => Array
(
[subdir_1] => Array
(
[file_1.mp4] => stdClass Object
(
[name] => file_1.mp4
)
[file_2.mp4] => stdClass Object
(
[name] => file_2.mp4
)
)
)
)
)
I browsed through other similar questions, and I've been trying to solve it with usort but I couldn't get my head around it. :S
Any idea?
Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements.
The usort() function in PHP sorts a given array by using a user-defined comparison function. This function is useful in case if we want to sort the array in a new manner. This function assigns new integral keys starting from zero to the elements present in the array and the old keys are lost.
The ksort() function sorts an associative array in ascending order, according to the key. Tip: Use the krsort() function to sort an associative array in descending order, according to the key. Tip: Use the asort() function to sort an associative array in ascending order, according to the value.
Use a recursive function:
// Note this method returns a boolean and not the array
function recur_ksort(&$array) {
foreach ($array as &$value) {
if (is_array($value)) recur_ksort($value);
}
return ksort($array);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With