0

I need the following array in alphabetical order (at all levels), but asort doesn't seem to work because I have a recursive call in my function (or so I think); it only partially sorts my array, so I'll have chunks of it that are alphabetized, but they'll be out of order.

Help!

Ex. Directory Listing:

apartments.html
js/
  application.js
  jquery.js
  something.js
css/
  reset.css
  master.css
preview.html
ab_restaurant_at_the_end_of_the_universe.jpg

Desired output:

array() { 
  [0] => string() "ab_restaurant_at_the_end_of_the_universe.jpg"
  [1] => string() "apartments.html"
  ["css"] => array() {
    [0] => string() "master.css"
    [1] => string() "reset.css"
  }
  ["js"] => array() {
    [0] => string() "application.js"
    [1] => string() "jquery.js"
    [2] => string() "something.js"
  }
  [2] => string() "preview.html"
}

function directory_list($directory) {
    $files = array();
    if (is_dir($directory)) {
      if ($curr_dir = opendir($directory)) {
      while (false !== ($file = readdir($curr_dir))) {
       if ($file != "." && $file != ".." && $file != "apartment" && $file != "blog") {
        if (is_dir($directory. "/" . $file)) {
          $files[$file] = directory_list($directory. "/" . $file);
        } else {
         $files[] = $file;
        }
       }
      }
      closedir($curr_dir);
     }
    }
    //asort($files); <-- doesn't work; sorts, but interrupts itself because of self-referencing call above (I think)
    return $files;
  }
4
  • Can you update your question to include a sample directory listing and the expected output? Commented Feb 23, 2010 at 17:44
  • -1 for not providing requested information. Commented Feb 23, 2010 at 18:12
  • Errr... Your desired output isn't in alphabetical order? Entry 0 and 1 should be switched (ab < ap). Commented Feb 23, 2010 at 19:41
  • @Wim Vandersmissen - Haha! You are too right; corrected. I feel like I spend more time typing the question than actually working on fixing it. Ah, c'est la vie... thanks. Commented Feb 23, 2010 at 20:00

1 Answer 1

1

If you change $files[] = $file; to $files[$file] = $file;, then you can use ksort() where you tried to use asort()

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.