1

I read recursively a folder and I got a multidimensional array like this:

Array
(
   [folder1] => Array
       (
           [sub-folder1] => Array
               (
                   [0] => sub-folder-1-file1.xx
                   [1] => sub-folder-1-file2.xx
                   [2] => sub-folder-1-file3.xx
               )

            [0] => folder-1-file1.xx
            [1] => folder-1-file2.xx
            [2] => folder-1-file3.xx
            [3] => folder-1-file4.xx
            [sub-folder2] => Array
                (
                   [0] => sub-folder-2-file1.xx
                   [1] => sub-folder-2-file1.xx
                )
  ...

I would like to sort it like

(
   [folder1] => Array
       (
            [0] => folder-1-file1.xx
            [1] => folder-1-file2.xx
            [2] => folder-1-file3.xx
            [3] => folder-1-file4.xx
            [sub-folder1] => Array
               (
                   [0] => sub-folder-1-file1.xx
                   [1] => sub-folder-1-file2.xx
                   [2] => sub-folder-1-file3.xx
               )
            [sub-folder2] => Array
                (
                   [0] => sub-folder-2-file1.xx
                   [1] => sub-folder-2-file1.xx
                )

like when we list by Type and not simply by Name.

I guess I must use usort but I can't figure it out properly: here my work:

usort($array, function($a, $b){
    if ( (is_array($a) && is_array($b)) || (!is_array($a) && !is_array($b)) )
       return 0;
    if ( is_array($a) )
       return -1;
    return 1;
});

Any help will be appreciated. Thanks.

I SOLVED LIKE THIS:

 foreach ($array as $key => $value)
 {
    ksort($array[$key], SORT_STRING);
 }
1
  • 1
    use ksort() instead. Commented Feb 27, 2015 at 16:03

1 Answer 1

1

What you can do is use ksort() function and pass the sorting type required as your second parameter.

Say your array's name is $test then you need something like this:

ksort($test['folder1'], SORT_STRING); //SORT_STRING compares items as strings

if you do a

echo '<pre>',print_r($test,1),'</pre>';

you will be able to see the result you want.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.