【问题标题】:Retrieving a single image from multiple subdirectories with PHP使用 PHP 从多个子目录中检索单个图像
【发布时间】:2013-06-10 17:16:58
【问题描述】:

我的 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。

【问题讨论】:

    标签: php image file random directory


    【解决方案1】:

    好的,这就是我所做的,而且效果很好......

    // 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>";
    

    【讨论】:

      【解决方案2】:

      查看RecursiveDirectoryIterator 并查看其中的示例。

      【讨论】:

        猜你喜欢
        • 2013-07-18
        • 2020-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-06
        相关资源
        最近更新 更多