我想在以下目录中列出目录和文件:
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);
答案 0 :(得分: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
)
答案 1 :(得分: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) */
}