使用PHP从多个子目录检索单个图像


Retrieving a single image from multiple subdirectories with PHP

我的PHP显然不是那么好,我正在使用一个看似缓慢的方法从名为gallery/的文件夹中的子文件夹检索图像。理想情况下,我希望从任何一个子目录中随机选择一个图像(而不是每个图像),并显示在一个小HTML标记中。我知道glob(),但我不能让它以我想要的方式工作,所以这是我一直在使用的,只是从子文件夹中拉出每一个图像:

<?php
echo "<html><head></head><body>";
function ListFiles($dir) {
    if($dh = opendir($dir)) {
        $files = Array();
         $inner_files = Array();
        while($file = readdir($dh)) {
            if($file != "." && $file != ".." && $file[0] != '.') {
                if(is_dir($dir . "/" . $file)) {
                    $inner_files = ListFiles($dir . "/" . $file);
                    if(is_array($inner_files)) $files = array_merge($files, $inner_files);
                } else {
                    array_push($files, $dir . "/" . $file);
                }
            }
        }
        closedir($dh);
        shuffle($files);
        return $files;
    }
}
foreach (ListFiles('gallery') as $key=>$file){
    echo "<div class='"box'" style='"margin: 3px;border: 1px dotted #999; display: inline-    block; '"><img src='"$file'"/></div>";
}

echo "</body></html>";
?>

这很好,但它不是很可扩展,我知道glob可以在这里使用。

参见RecursiveDirectoryIterator,并查看它的示例

好了,这就是我所做的,它运行得很好…

// Collects every path name under gallery/ for a .png
$imgs = glob("gallery/*/*.png");
//Mixes up the array
shuffle($imgs);
//Print it out just to make sure
//print_r($imgs);
//array_rand returns single key values, making it perfect to return a *single* image
$k = array_rand($imgs);
$v = $imgs[$k];
//Print out images
echo "<div class='"box'" style='"margin: 3px;border: 1px dotted #999; display: inline-block; '"><img src='"$v'"/></div>";