如何从所有子目录中获取图像名称?

I have used following php code to get all images names from relevant directory.

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

This one works perfectly. But I want to get all images file names within all sub directories from relevant directory. Parent directory does not contain images and all the images contain in sub folders as folows.

  • Parent Dir
    • Sub Dir
      • image1
      • image2
    • Sub Dir2
      • image3
      • image4

How I go through the all sub folders and get the images names?

Try following. To get full directory path, merge with parent directory.

$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>";
       }
   }
}

Utilizing recursion, you can make this quite easily. This function will indefinitely go through your directories until each directory is done searching. THIS WAS NOT TESTED.

$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');