Search code examples
phparrayssortingmultidimensional-arrayfilesystems

Recursively sort a multidimensional array representing a file system with directories as keys and filenames as indexed subarrays


I need to sort a multidimensional array which represents filesystem structure. How can I sort the directories by their keys and the filenames by their values?

[
    'dir1' => [
        'dir2' => [
            'dir3' => [
                'dir4' => [
                    'file1.php',
                    'abc.php'
                ]
            ],
            'file2.php',
            'abc.php'
        ]
    ],
    'abc' => [
        'abc' => [
            'abc' => [
                'file5.php'
            ]
        ]
    ]
]

Solution

  • http://php.net/sort#51088

    replace sort($a) at the beginning of the mulsort function by ksort($a)

    EDIT: sorry, just change the mulsort code to :

    function mulsort(&$a)
    {
     ksort($a);
     foreach($a as &$value)
        if (is_array($value))
            mulsort($value);
    }