0

我想列出目录中的目录和文件,例如:

Array(
    [0] => 2014
    [1] => images
    [2] => videos
)

这个数组中的所有目录都在我网站的“web_public”目录中。但是其中还有一些我不想阅读的其他目录。完整的 web_public 是:

2014
images
videos
css
js
... and so on

这是我正在做但不起作用的事情:

$objects = array();
foreach($dirs_to_read as $dir) {
    $dir = 'web_public/'.$dir;
    $objects = array_merge($objects, new RecursiveDirectoryIterator($dir));                
}   
$objects = new RecursiveIteratorIterator($objects);
4

2 回答 2

1

从 PHP 5 开始,您可以使用RecursiveDirectoryIterator来获取文件数组。例如:

$path = __DIR__;

$directory = new \RecursiveDirectoryIterator(
    $path,
    RecursiveDirectoryIterator::SKIP_DOTS
    | RecursiveDirectoryIterator::CURRENT_AS_PATHNAME
    | RecursiveDirectoryIterator::KEY_AS_FILENAME
);

$iterator = new \RecursiveIteratorIterator($directory);
$array    = iterator_to_array($iterator);

print_r($array);

输出类似:

Array
(
    [demo.php] => /path/tp/demo.php
)
于 2014-03-01T23:10:06.500 回答
1

这需要使用AppendIterator. 示例用法:

$ai = new AppendIterator;
foreach( $dirs_to_read as $dir )
{
    // append RecursiveDirectoryIterator (wrapped in RecursiveIteratorIterator)
    // you need RecursiveIteratorIterator as well,
    // to iterate all depths of the RecursiveDirectoryIterator, in one go
    $ai->append( new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator( 'web_public/' . $dir ),
        RecursiveIteratorIterator::SELF_FIRST
    ) );
}

// iterate the AppendIterator
foreach( $ai as $file )
{
    /* do something with the file (which is an SplFileInfo instance) */
}
于 2014-03-01T23:21:38.327 回答