【问题标题】:How to get image names from all sub directories?如何从所有子目录中获取图像名称?
【发布时间】:2016-10-12 08:53:15
【问题描述】:

我使用以下 php 代码从相关目录中获取所有图像名称。

$dir = "images";
$images = scandir($dir);
$listImages=array();
foreach($images as $image){
    $listImages=$image;
    echo ($listImages) ."<br>";
}

这个很完美。但我想从相关目录中获取所有子目录中的所有图像文件名。父目录不包含图像,所有图像都包含在子文件夹中,如下所示。

  • 父目录
    • 子目录
      • 图像1
      • 图像2
    • 子目录2
      • 图像3
      • 图像4

我如何浏览所有子文件夹并获取图像名称?

【问题讨论】:

标签: php


【解决方案1】:

尝试关注。要获取完整目录路径,请与父目录合并。

$path = 'images'; // '.' for current
   foreach (new DirectoryIterator($path) as $file) {
   if ($file->isDot()) continue;

   if ($file->isDir()) {
       $dir = $path.'/'. $file->getFilename();

   $images = scandir($dir);
       $listImages=array();
       foreach($images as $image){
           $listImages=$image;
           echo ($listImages) ."<br>";
       }
   }
}

【讨论】:

    【解决方案2】:

    利用递归,您可以很容易地做到这一点。此功能将无限期地遍历您的目录,直到完成每个目录的搜索。这没有经过测试。

    $images = [];
    
    function getImages(&$images, $directory) {
        $files = scandir($directory); // you should get rid of . and .. too
    
        foreach($files as $file) {
            if(is_dir($file) {
                getImages($images, $directory . '/' . $file);
            } else {
                array_push($images, $file); /// you may also check if it is indeed an image
            }
        }
    }
    
    getImages($images, 'images');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-08
      • 2019-10-25
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      相关资源
      最近更新 更多