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 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘