简体   繁体   中英

Create a double array from a directory's subdirectories followed by files

I have a directory named images which contains subdirectories. Each of these subdirectories contain images. What I wanted to do is write a function that returns a double array indexed as $images[$subDirectory][$fileName] to make iterating over them simple later.

I tried writing the code below which seems to work just fine, however I had to add code like:

if ($subName === "." || $subName === ".." || $subName === ".DS_Store") continue;

Which makes me feel like I am doing something wrong. Is there a better way to go about this or is this just a required part of the solution?

function getImages($inDirectory) {
    if (!is_dir($inDirectory))
        failureExit("Not a directory: ".$inDirectory);

    if (!$dir = opendir($inDirectory))
        failureExit("Could not open: ".$inDirectory);

    $out = array();
    while (($subName = readdir($dir)) !== false) {
        if ($subName === "." || $subName === ".." || $subName === ".DS_Store") continue;
        if (is_dir($inDirectory."/".$subName)) {
            if (!$subDir = opendir($inDirectory."/".$subName))
                failureExit("Could not open: ".$inDirectory."/".$subDir);

            $out[$subName] = array();
            while (($subSubName = readdir($subDir)) !== false) {
                if ($subSubName === "." || $subSubName === ".." || $subSubName === ".DS_Store") continue;
                $out[$subName][$subSubName] = 0;
            }
            closedir($subDir);
        }
    }
    closedir($dir);

    return $out;
}

$images = getImages("images");
print_r($images);

If you use RecursiveDirectoryIterator you can take advantage of the SKIP_DOTS flag to skip . and .. , however, you'll still have to specify any custom directories such as .DS_Store that you want to skip.

$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator(".",FileSystemIterator::SKIP_DOTS)
);

#note the leading './'
$skip_paths = array('./.DS_Store','./.SKIP_ME'); 
$images = array();

#$image an SPLFileInfo object
#http://php.net/manual/en/class.splfileinfo.php
foreach ($iterator as $image) {
    if($iterator->getDepth() === 1 && !in_array($image->getPath(),$skip_paths))
        $images[$image->getPath()][$image->getFilename()] = $image;
}

print_r($images);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM