Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm having a directory with this structure :

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

I can create a function to complete the work but the RecursiveDirectoryIterator class is much faster and less memory usage this time. How can I use RecursiveDirectoryIterator to list these directory into 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"  
        )  
    )  
)  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
325 views
Welcome To Ask or Share your Answers For Others

1 Answer

Well, to recursively iterate over the RecursiveIterator, you need a RecursiveIteratorIterator (I know it seems redundant, but it's not)...

However, for your particular case (Where you're looking to generate a structure rather than just visit all of the 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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...