I want to list directories and files in directories like:
Array(
[0] => 2014
[1] => images
[2] => videos
)
All of the directories in this array are in the "web_public" directory of my website. But there are some other directories within it which I don't want to read. The complete web_public is:
2014
images
videos
css
js
... and so on
Here is what I'm doing but doesn't work:
$objects = array();
foreach($dirs_to_read as $dir) {
$dir = 'web_public/'.$dir;
$objects = array_merge($objects, new RecursiveDirectoryIterator($dir));
}
$objects = new RecursiveIteratorIterator($objects);
From PHP 5 you can use RecursiveDirectoryIterator
to get file array. For example:
$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);
Outputs something like:
Array
(
[demo.php] => /path/tp/demo.php
)
This calls for use of the AppendIterator
. Example usage:
$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) */
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.