Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading