skip to Main Content

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?

2

Answers


  1. 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);
    
    Login or Signup to reply.
  2. You can either convert this array to collection and use relevant collection methods to sort.

    Use Arr utility of laravel, flatten the array and sort.

    use recursive sorting, from standard library of PHP.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search