How to sort all dimensions of a multidimensional array in PHP – Laravel 10?

I have a multidimensional array like this:

  0 => array:2 [▼
    "name" => "Game.exe"
    "size" => "9.8 MiB"
  ]
  1 => array:2 [▼
    "name" => "Launcher.exe"
    "size" => "3.9 MiB"
  ]
    "/USRDIR" => array:4 [▼
        0 => array:2 [▶]
        1 => array:2 [▶]
        "/movie" => array:2 [▶]
        2 => array:2 [▶]
    ]
  2 => array:2 [▼
    "name" => "bink2w32.dll"
    "size" => "286.5 KiB"
  ]

As you can see, this array represents a file structure. Files that are inside folders are represented as arrays with a size and name, inside of arrays representing their folders, all inside of a root folder. This file structure contains multiple levels of subfolders containing files, and as such, the array is a deep multidimensional array.

I want to sort all arrays so that the folders/subfolders (key = string starting with "/") are always the first, sorted alphabetically, and then come the files in the respective folder, sorted alphabetically by the value of ‘name’. How do I do this?

>Solution :

Try this.

function sortFileStructure(&$array) {
    $folders = [];
    $files = [];

    foreach ($array as $key => &$element) {
        if (is_array($element)) {
            if (isset($element['name'])) {
                $files[$key] = $element;
            } else {
                sortFileStructure($element);
                $folders[$key] = $element;
            }
        }
    }
    ksort($folders);
    $array = $folders + $files;
}

call this function wherever you need it.

sortFileStructure($yourArray);

Leave a Reply