Pull all images from multiple directories and display them with PHP

此生再无相见时 提交于 2019-12-11 13:34:47

问题


I have a folder on my server called 'images', and within that folder I could have a single folder to as many as 10 folders that contain images.

Instead of writing a tag for each image

<img src="images/people/001.jpg">
<img src="images/landscape/001.jpg">

etc etc

Can I use PHP to get all the images in all the folders in the main directory 'images'?

I have VERY little experience with PHP, so this is something I am struggling with.

I need php to return an array of '<div class="box"><img src="images/FOLDER/IMAGENAME.jpg"></div>'

Maybe someone can help.


回答1:


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);
        return $files;
    }
}
foreach (ListFiles('/path/to/images') as $key=>$file){
    echo "<div class=\"box\"><img src=\"$file\"/></div>";
}

Something like this?




回答2:


A simpler soluton. You can use built-in glob function. Assuming that all of your images are .jpg:

$result = array();
$dir    = 'images/';

foreach(glob($dir.'*.jpg') as $filename) {
    $result[] = "<div class=\"box\"><img src=\"$filename\"></div>";
}

Then you can echo each element of $result or whatever you want.



来源:https://stackoverflow.com/questions/9628369/pull-all-images-from-multiple-directories-and-display-them-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!