dpzzkfb1244 2013-03-22 19:07
浏览 32
已采纳

RecursiveDirectoryIterator - 在找到的路径中的第一个字符串实例上发出信号

I'm using RecursiveDirectoryIterator(). I have a situation whereby I want to signal to my program that there should be a single file created upon the first instance of a specified string in a directory hierarchy. I'm hoping that RecursiveDirectoryIterator() is suitable for this, but if there's another option that would make more sense, I'm also open to that.
See below for details on my question... Thanks.

code:

$in_dir = 'none';
$path = '.';
$dir  = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);

foreach($files as $object){
  //if this is a directory... find out which one it is.
  if($object->isDir()){
    if(strpos($object->getPathname(), 'dir1') == true){
      //i need a file (file1.txt) created here, upon the first instance found
      $in_dir = 'dir1';
    }else if(strpos($object->getPathname(), 'dir2') == true){
      //i need a file (file2.txt) created here, upon the first instance found
      $in_dir = 'dir2';
    }
}
  • 写回答

1条回答 默认 最新

  • doushui20090526 2013-03-22 19:26
    关注

    You just need to keep track of the first time you visit the directory...

    $in_dir = 'none';
    $path = '.';
    $dir  = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);
    // not seen yet
    $foundDir1 = false;
    $foundDir2 = false;
    
    foreach($files as $object){
        //if this is a directory... find out which one it is.
        if($object->isDir()){
            if(strpos($object->getPathname(), 'dir1') == true){
                //i need a file (file1.txt) created here, upon the first instance found
                if (!$foundDir1) {
                    // first time we've seen it, create file...
    
                    // mark as found
                    $foundDir1 = true;
                }
            }else if(strpos($object->getPathname(), 'dir2') == true){
                //i need a file (file2.txt) created here, upon the first instance found
                if (!$foundDir2) {
                    // first time we've seen it, create file...
    
                    // mark as found
                    $foundDir2 = true;
                }
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi