用递归函数调用对数组进行排序?

时间:2010-02-23 17:39:51

标签: php sorting arrays recursion

我需要按字母顺序排列以下数组(在所有级别),但asort似乎不起作用,因为我在函数中有一个递归调用(或者我认为);它只是对我的数组进行了部分排序,因此我将使用按字母顺序排列的数据块,但它们将会出现故障。

帮助!

实施例。目录列表:

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

期望的输出:

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;
  }

1 个答案:

答案 0 :(得分:1)

如果您将$files[] = $file;更改为$files[$file] = $file;,那么您可以在尝试使用asort()的地方使用kso​​rt()