dongxing1960 2010-02-23 17:39
浏览 101
已采纳

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

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;
  }
  • 写回答

1条回答 默认 最新

  • dongtaigan1594 2010-02-23 21:56
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀