返回层次结构中的所有唯一目录

时间:2014-11-07 01:21:14

标签: php recursion iterator directory

我正在使用RecursiveDirectoryIterator扫描给定根目录中的所有文件和文件夹。这很好用,但我想跟踪该列表中的所有唯一目录,因此我不确定RecursiveDirectoryIterator是否可行。

我的目录结构为

-a ->b ->c -one ->two ->three

这是我的代码:

<?php

function test($dir){

    $in_dir = 'none';
    $currdir = 'none';

    $thisdir = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($thisdir, RecursiveIteratorIterator::SELF_FIRST);

    foreach($files as $object){
    //if this is a directory... find out which one it is.
    if($object->isDir()){

        //figure out if we have changed directories...
        $currdir = realpath($object->getPath());

        if(strpos($currdir, '.') == false){
        $test = strcmp($currdir, $prevdir);
        if($test){
            echo "current dir changing: ", $currdir, "\n";
            $prevdir = $currdir;
        }
        }
    }
    }
}

test('fold');   
?>

我从中获得的是以下内容:

current dir changing: /Users/<usr>/Desktop/test/fold

current dir changing: /Users/<usr>/Desktop/test/fold/a

current dir changing: /Users/<usr>/Desktop/test/fold/a/b

current dir changing: /Users/<usr>/Desktop/test/fold

current dir changing: /Users/<usr>/Desktop/test/fold/one

current dir changing: /Users/<usr>/Desktop/test/fold/one/two

...但我只想要唯一的目录。

1 个答案:

答案 0 :(得分:1)

它可能是循环中对象比较的方法,它返回重复项,因为迭代器在解析文件夹时在目录树中上下移动。

以下对我有用。我还使用array_unique()确认没有欺骗作为冗余。

$dirArray = []; // the array to store dirs
$path = realpath('/some/folder/location');

$objects = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($path), 
    RecursiveIteratorIterator::SELF_FIRST
);

// loop through all objects and store names in dirArray[]
foreach($objects as $name => $object){
  if ($object->isDir()) {
    $dirArray[] = $name;
  }
}

// make sure there are no dupes
$result = array_unique($dirArray);

// print array out
print_r($result);