Reputation: 1414
So I want to show whole directory and sub directories.
According PHP Doc,
The RecursiveDirectoryIterator provides an interface for iterating recursively over filesystem directories
Here is my code:
$it = new RecursiveDirectoryIterator("c:\php_win");
foreach ($it as $dir) {
var_dump($dir->getFilename());
}
Above code only shown one level directory, all sub directories not been shown.
I know I have to use RecursiveIteratorIterator to get all sub directories, but i just do not know why I need to use a RecursiveIteratorIterator iterator.
what is "iterating recursively over filesystem directories" mean? any web links which explains why we need a IteratorIterator?
Upvotes: 2
Views: 2099
Reputation: 14150
I've turned into a gist a class (RecursiveDirectoryIterator
) that can read a directory with all its children and output a JSON or just an array.
https://gist.github.com/jonataswalker/3c0c6b26eabb2e36bc90
And a tree viewer of the output
http://codebeautify.org/jsonviewer/067c13
Upvotes: 0
Reputation: 197777
The RecursiveDirectoryIterator
is a class implementing the RecursiveIterator
interface.
The RecursiveIteratorIterator
is a class implementing the Iterator
interface.
With a foreach
traversal over it, it will take an object implementing RecursiveIterator
and do a recursive traversal (tree traversal) on it, here in PHP not only rewinding, fetching current, advancing next and checking validity but also checking if children exists and then internally iterating over these children, too.
So the RecursiveIteratorItertor
is providing object traversal in linear order while performing a tree traversal over a concrete RecursiveIterator
implementaion.
So the RecursiveDirectoryIterator
is only the container. You can iterate over it straight away (e.g. with foreach), but that linear order object iteration would not do the tree traversal.
That is why the RecursiveIteratorIterator
is there, it offers that tree traversal.
Which is exactly your case: Direct iteration over RecursiveDirectoryIterator
only does linear object traversal. Only the RecursiveIteratorIterator
knows how to do tree traversal on objects implementing the RecursiveIterator
interface. As it implements the Iterator
interface itself, it is then possible to do linear object traversal over the tree traversal.
See as well my answer to How does RecursiveIteratorIterator works in php, it covers the directory iterators exemplary to show the different modes of tree traversal that are possible.
Upvotes: 2