John K
John K

Reputation: 105

RecursiveDirectoryIterator to echo list separated by folders

is there any way for RecursiveDirectoryIterator to echo files in subfolders separately based on folder and not all together?

Here is my example. I have a folder (event), which has multiple subfolders (logo, people, bands). But subfolder names vary for certain events, so I can't simply set to look inside these three, I need a "wildcard" option. When I use RecursiveDirectoryIterator to echo out all images from these folders, it works, but I would like to separate these based on subfolder, so it echoes out folder name and all images from within below and then repeats for the next folder and so on.

Right now I use this:

<?php 
$directory = "path/to/mainfolder/";
foreach (new RecursiveIteratorIterator(new 
RecursiveDirectoryIterator($directory,RecursiveDirectoryIterator::SKIP_DOTS)) as $filename)
{
  echo '<img src="'.$filename.'">';
}
?>

So, how do I make this echo like:
Logo
image, image, image
People
image, image, image
...

Thanks in advance for any useful tips and ideas.

Upvotes: 1

Views: 305

Answers (1)

Wee Zel
Wee Zel

Reputation: 1324

for me, code is more readable when you put objects into variables with descriptive names then pass those on when instantiating other classes. I've used the RegexIterator() over the RecursiveFilterIterator() to filter just image file extensions (didn't want to get into extending the RecursiveFilterIterator() class for example). The rest of the code is simple iterating, extracting strings and page breaking.
NOTE: there is no error handling, best to add a try/catch to manage exceptions

<?php
$directory = 'path/to/mainfolder/';

$objRecursiveDirectoryIterator = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS);
$objRecursiveIteratorIterator = new RecursiveIteratorIterator($objRecursiveDirectoryIterator);
// use RegexIterator() to grab only image file extensions
$objRegexIterator = new RegexIterator($objRecursiveIteratorIterator, "~^.+\.(bmp|gif|jpg|jpeg|img)$~i", RecursiveRegexIterator::GET_MATCH);

$lastPath = '';
// iterate through all the results
foreach ($objRegexIterator as $arrMatches) {
    $filename = $arrMatches[0];
    $pos = strrpos($filename, DIRECTORY_SEPARATOR); // find position of last DIRECTORY_SEPARATOR
    $path = substr($filename, 0, $pos); // path is everything before
    $file = substr($filename, $pos + 1); // file is everything after
    $myDir = substr($path, strrpos($path, DIRECTORY_SEPARATOR) + 1); // directory the file sits in
    if ($lastPath !== $path) { // is the path the same as the last
        // display page break and header
        if ($lastPath !== '') {
            echo "<br />\n";
            echo "<br />\n";
        }
        echo $myDir ."<br />\n";
        $lastPath = $path;
    }
    echo $file . " ";
}

Upvotes: 1

Related Questions