我正在使用RecursiveDirectoryIterator()。我有一种情况,我希望向我的程序发出一个信号,即在目录层次结构中指定字符串的第一个实例上应该创建一个单个文件。我希望RecursiveDirectoryIterator()适合这个,但是如果有另一个更有意义的选项,我也会对此持开放态度。
有关我的问题的详细信息,请参阅下文...谢谢。
代码:
$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';
}
}
答案 0 :(得分:2)
您只需要跟踪第一次访问目录...
$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;
}
}
}
}