草庐IT

php - 遍历目录的所有子目录

coder 2024-04-21 原文

我有一个应该很简单的任务,

  • 给定一条路径,在所有子项(深度 1 级)中搜索 less 文件夹。
  • 如果找到文件夹,将完整路径作为键添加到数组
  • 将键的值设置为相同的路径,但将 less 替换为 css
  • 在 less 目录中递归循环所有子目录
  • 按照与原始目录相同的方式添加子目录

所以,给定这个结构

Note: All items below except for randomfile are directories

matthew@vaio:/var/www/constructor/public/bundles$ tree
.
├── first
│   └── less
│       ├── secondtester
│       └── tester
│           ├── anothersubtester
│           ├── randomfile
│           └── subtester
├── second
│   └── less
│       ├── secondtester
│       └── tester
│           ├── anothersubtester
│           ├── randomfile
│           └── subtester
└── third
    └── noless
        ├── secondtester
        └── tester
            ├── anothersubtester
            ├── randomfile
            └── subtester

18 directories, 3 files

我想以这个数组结束(注意我已经截断了这里的路径只是为了让它更容易阅读)

Array
    (
    [/b/second/less] => /b/second/css
    [/b/second/less/secondtester] => /b/second/css/secondtester
    [/b/second/less/tester] => /b/second/css/tester
    [/b/second/less/tester/subtester] => /b/second/css/tester/subtester
    [/b/second/less/tester/anothersubtester] => /b/second/css/tester/anothersubtester
    [/b/first/less] => /b/first/css
    [/b/first/less/secondtester] => /b/first/css/secondtester
    [/b/first/less/tester] => /b/first/css/tester
    [/b/first/less/tester/subtester] => /b/first/css/tester/subtester
    [/b/first/less/tester/anothersubtester] => /b/first/css/tester/anothersubtester
)

现在我有下面的代码,但我认为这根本没有优化,例如我知道有 RecursiveIteratorIterators 等,但我不知道如何将它们用于此任务,因此不得不求助于执行提升的递归函数。基本上,我想知道如何编写此代码以更好地对其进行优化:

$directories = array();
$bundlePath = realpath('/public/bundles');

function lessSearcher($lessPath, $cssPath){
    $directories = array($lessPath => $cssPath);

    $lessDirs = new DirectoryIterator($lessPath);
    foreach ($lessDirs as $lessDir) {
        //we only want the directories and not the .'s
        if ($lessDir->isDot() || !$lessDir->isDir()) continue;
        $lessCurrent = $lessPath . '/' . $lessDir->getFileName();
        $cssCurrent = $cssPath . '/' . $lessDir->getFileName();
        $directories[$lessCurrent] = $cssCurrent;
        $directories = array_merge($directories, lessSearcher($lessCurrent, $cssCurrent));
    }

    return $directories;
}

$bundles = new DirectoryIterator($bundlePath);
foreach ($bundles as $bundle) {
    //we only want the directories and not the .'s
    if($bundle->isDot() || !$bundle->isDir()) continue;
    //we only want the directories that have a less directory
    if(!realpath($bundlePath.'/'.$bundle->getFileName().'/less')) continue;

    $lessPath = realpath($bundlePath . '/' . $bundle->getFileName()) . '/less';
    $cssPath = realpath($bundlePath . '/' . $bundle->getFileName()) . '/css';

    $directories = array_merge($directories, lessSearcher($lessPath, $cssPath));
}

最佳答案

我认为代码已正确优化。
我制作了一个列出所有目录和子目录的脚本,然后删除那些没有“less”目录的脚本,并为有它的目录创建一个新数组。
然后我用 1000 次循环测试了你和我的。你的脚本平均花费了 0.93s 而我的脚本花费了 1.27s。所以在我看来,您的代码没问题。

关于php - 遍历目录的所有子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14138538/

有关php - 遍历目录的所有子目录的更多相关文章

  1. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  2. ruby - 如何以所有可能的方式将字符串拆分为长度最多为 3 的连续子字符串? - 2

    我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123

  3. ruby-on-rails - active_admin 目录中的常量警告重新声明 - 2

    我正在使用active_admin,我在Rails3应用程序的应用程序中有一个目录管理,其中包含模型和页面的声明。时不时地我也有一个类,当那个类有一个常量时,就像这样:classFooBAR="bar"end然后,我在每个必须在我的Rails应用程序中重新加载一些代码的请求中收到此警告:/Users/pupeno/helloworld/app/admin/billing.rb:12:warning:alreadyinitializedconstantBAR知道发生了什么以及如何避免这些警告吗? 最佳答案 在纯Ruby中:classA

  4. ruby-on-rails - 跳过状态机方法的所有验证 - 2

    当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested

  5. ruby - Nokogiri 剥离所有属性 - 2

    我有这个html标记:我想得到这个:我如何使用Nokogiri做到这一点? 最佳答案 require'nokogiri'doc=Nokogiri::HTML('')您可以通过xpath删除所有属性:doc.xpath('//@*').remove或者,如果您需要做一些更复杂的事情,有时使用以下方法遍历所有元素会更容易:doc.traversedo|node|node.keys.eachdo|attribute|node.deleteattributeendend 关于ruby-Nokog

  6. ruby - 获取模块中定义的所有常量的值 - 2

    我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c

  7. ruby-on-rails - 如何在 Gem 中获取 Rails 应用程序的根目录 - 2

    是否可以在应用程序中包含的gem代码中知道应用程序的Rails文件系统根目录?这是gem来源的示例:moduleMyGemdefself.included(base)putsRails.root#returnnilendendActionController::Base.send:include,MyGem谢谢,抱歉我的英语不好 最佳答案 我发现解决类似问题的解决方案是使用railtie初始化程序包含我的模块。所以,在你的/lib/mygem/railtie.rbmoduleMyGemclassRailtie使用此代码,您的模块将在

  8. 【Java入门】使用Java实现文件夹的遍历 - 2

    遍历文件夹我们通常是使用递归进行操作,这种方式比较简单,也比较容易理解。本文为大家介绍另一种不使用递归的方式,由于没有使用递归,只用到了循环和集合,所以效率更高一些!一、使用递归遍历文件夹整体思路1、使用File封装初始目录,2、打印这个目录3、获取这个目录下所有的子文件和子目录的数组。4、遍历这个数组,取出每个File对象4-1、如果File是否是一个文件,打印4-2、否则就是一个目录,递归调用代码实现publicclassSearchFile{publicstaticvoidmain(String[]args){//初始目录Filedir=newFile("d:/Dev");Datebeg

  9. ruby - Chef Ruby 遍历 .erb 模板文件中的属性 - 2

    所以这可能有点令人困惑,但请耐心等待。简而言之,我想遍历具有特定键值的所有属性,然后如果值不为空,则将它们插入到模板中。这是我的代码:属性:#===DefaultfileConfigurations#default['elasticsearch']['default']['ES_USER']=''default['elasticsearch']['default']['ES_GROUP']=''default['elasticsearch']['default']['ES_HEAP_SIZE']=''default['elasticsearch']['default']['MAX_OP

  10. ruby-on-rails - 没有这样的文件或目录 - 用 Mini Magick 识别 - 2

    在我让另一个人重做我的前端UI之前,我的Rails应用程序运行平稳。我已经尝试解决此错误3天了。这是错误:Nosuchfileordirectory-identifyExtractedsource(aroundline#59):575859606162@post=Post.find(params[:id])authorize@postif@post.update_attributes(post_params)flash[:notice]="Postwasupdated."redirect_to[@topic,@post]else{"utf8"=>"✓","_method"=>"patc

随机推荐