To sort the variable depth structure use recursion to traverse all levels. Identify directories, not by their key, but by their value datatype -- if an array, then it is a directory which needs to be naturally sorted by key. If dealing with a leafnode, then the indexes do not need to be preserved and the values should be sorted naturally.
By separating the two item types, sorting correctly is simple. After soring each "bucket", merge them together to overwrite $array. Note that if you have a directory named 0, then this numeric key will bump up the starting point of any index-keyed files in the same directory.
This will present your directories and files in a logical, yet human-friendly way.
Code: (Demo)
function sortFileSystem(array &$array)
{
$dirs = [];
$files = [];
foreach ($array as $k => &$v) {
if (is_array($v)) {
(__FUNCTION__)($v); // recurse
$dirs[$k] = $v; // preserve key
} else {
$files[] = $v; // key is unneeded
}
}
ksort($dirs, SORT_NATURAL);
sort($files, SORT_NATURAL);
$array = array_merge($dirs, $files); // put dirs before files
}
sortFileSystem($array);
var_export($array);