Use RecursiveDirectoryIterator to map directories and files to an array?

I have a directory with this structure:

  • Primary /
    • | - images /
      • | - file1.jpg
      • | - file2.jpg
      • | - file3.jpg
    • | - documents /
      • | - private /
        • | --- blahblahblah.docx
      • | - test.doc
      • | - test.xls
      • | - test.txt

I can create a function to shut down, but the RecursiveDirectoryIterator class is much faster and uses less memory this time. How can I use RecursiveDirectoryIterator to list these directories in an array like this:

array( "main/" => array( "images/" => array( "file1.jpg", "file2.jpg", "file3.jpg" ), "documents/" => array( "private/" => array( "blahblahblah.docx" ), "test.doc", "test.xls", "test.txt" ) ) ) 
+4
source share
2 answers

Well, to recursively RecursiveIterator over a RecursiveIterator , you need a RecursiveIteratorIterator (I know it is superfluous, but it is not) ...

However, for your specific case (where you want to create a structure, and not just visit all nodes), I think regular recursion would be better suited ...

 function DirectoryIteratorToArray(DirectoryIterator $it) { $result = array(); foreach ($it as $key => $child) { if ($child->isDot()) { continue; } $name = $child->getBasename(); if ($child->isDir()) { $subit = new DirectoryIterator($child->getPathname()); $result[$name] = DirectoryIteratorToArray($subit); } else { $result[] = $name; } } return $result; } 

Edit it to work with non-recursive iterators ...

+12
source

Just for writing to others, I turned into a gist class ( RecursiveDirectoryIterator ) that can read a directory with all its children and output JSON or just an array.

https://gist.github.com/jonataswalker/3c0c6b26eabb2e36bc90

And the output tree viewer

http://codebeautify.org/jsonviewer/067c13

0
source

All Articles