从同一个php函数中的第二个目录输出文件

时间:2010-03-03 20:43:43

标签: php directory scandir

我有以下代码从目录im /输出图像,我如何调整它以输出来自另一个被称为/ /(例如)的视频的图像?至于在当前的标签下回显另一个img标签?

<?php
    $imgDir = "im/";

    $images = scandir($imgDir); 
    $ignore = array( ".", ".." ); 

    natsort($images);

    foreach($images as $file)
       {
    if(!in_array($file, $ignore))
       {
    echo "<div id=\"slideWrapper\">\n";
    echo "<img src=\"im/$file\" width=\"1000\" height=\"683\" alt=\"$files\" />\n";
    echo "</div>\n";
    };
    }
?>

2 个答案:

答案 0 :(得分:0)

我会按以下方式执行 - 为数组交换$ imgDir。 $ images数组现在包含路径和文件名。

<?php
    $imgDirs = array("im/", "out/");
    $images = array();

    // take one of the given directories
    foreach($imgDirs as $imgDir)
    {
       // open a directory reader for this given directory
       $dh = opendir($imgDir);
       // read a single filename of this directory (stop loop if there is no more file)
       while (false !== ($filename = readdir($dh))) 
       {
           // ignore '.' and '..'
           if($filename != '.' && $filename != '..')
           {
              // add the directory and filename to the images array
              // all images, regardless of the folder, are stored in one array :)
              $images[] = $imgDir . $filename;
           }
       } 
       closedir($dh);
    }

    natsort($images);

    // loop for every image
    foreach($images as $file)
    {
       // for every img, echo a div-img-/div-combination
       echo "<div id=\"slideWrapper\">\n";
       echo "<img src=\"$file\" width=\"1000\" height=\"683\" alt=\"$file\" />\n";
       echo "</div>\n";
    }
?>

答案 1 :(得分:0)

相信这符合您的需求。

<?php
    $imgDir = 'im/';
    $imgDir2 = 'out/';
    $images = array();

    // open a directory reader for the first directory
    $dh = opendir($imgDir);
    // read a single filename of this directory (stop loop if there are no more files)
    while (false !== ($filename = readdir($dh))) 
    {
        // ignore '.' and '..'
        if($filename != '.' && $filename != '..')
        {
           // add the directory and filename to the images array
           $images[] = $filename;
        }
    }
    closedir($dh);

    natsort($images);

    // loop for every image
    foreach($images as $image)
    {
       // for every img, echo a div-2-images-div-combination
       echo '<div id="slideWrapper">';
       echo '<img src="'.$imgDir . $image.'" width="1000" height="683" alt="'.$image.'" />';
       echo '<img src="'.$imgDir2 . $image.'" width="1000" height="683" alt="'.$image.'" />';
       echo '</div>';
    }
?>

我建议使用单引号,因为您不必转义正常引号并且速度更快:)