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 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决