显示多个目录中的图像

时间:2010-11-05 15:27:47

标签: php

我想显示多个图像的图像。

我有这个主文件夹(背景),在这个DIR里面我有45个文件夹,每个文件夹有10-20个图像。

我想显示目录中的所有图像。

问候 Al3in

1 个答案:

答案 0 :(得分:0)

试试这个:

<?php
// Recursivly search through a directory and sub-directories for all
// image files. The returned result will be an array will all matches
// and their path (relative to the path sent in through the $dir argument)
//
// $dir       - Directory to search through
// $filetypes - Array of file extensions to match
// 
// Returns: Array() of files that match the $filetypes filter (or standard
//          image file extensions by default).
//
function recursiveFileSearch($dir = '.', $filetypes = null)
{
  if (!is_dir($dir))
    return Array();

  // create a regex filter so we only grab image files
  if (is_null($filetypes))
    $filetypes = Array('jpg','jpeg','gif','png');
  $fileFilter = '/\.('.implode('|',$filetypes).')$/i';

  // build a results array
  $images = Array();

  // open the directory and begin searching
  if (($dHandle = opendir($dir)) !== false)
  {
    // iterate all files
    while (($file = readdir($dHandle)) !== false)
    {
      // we don't want the . or .. directory aliases
      if ($file == '.' || $file == '..')
        continue;

      // compile the path for reference
      $path = $dir . DIRECTORY_SEPARATOR . $file;

      // is it a directory? if so, append the results
      if (is_dir($path))
        $results = array_merge($results, recursiveFileSearch($path,$filetypes));
      // must be a file, see if it matches our patter and add it if necessary
      else if (is_file($path) && preg_match($fileFilter,$file))
        $results[] = str_replace(DIRECTORY_SEPARATOR,'/',$path);
    }

    // close the directory when we're through
    closedir($dHandle);
  }

  // return the outcome
  return $results;
}
?>
<html><body><?php array_map(create_function('$i','echo "<img src=\"{$i}\" alt=\"{$i}\" /><br />";'),recursiveFileSearch('backgrounds')); ?></body></html>