0

我一直在努力解决这个问题。

我发现这段代码运行良好,取自官方 php 网站。但是,如果我将一张图像和一个 pdf 放在文件夹中,它就会显示出来。照片。

我需要一种非常简单的方法来扫描目录,检查其是否为 jpg,然后只显示一张照片。

请告诉我如何更改以下代码,或者我是否需要为我的需要编写一些不同的东西。

<?php // no access
.............

// globals 

.............

// make article title lower case

$str = strtolower($articleTitle); 

$files= scandir("images/gallery/".$str."/");
$photos = array();
        for ($x=0; $x<count($files); $x++){
        $files[$x]="images/gallery/".$str."/".$files[$x];
                if (is_dir($files[$x])){
                $thisfolder=scandir($files[$x]);
                for ($f=0; $f<count($thisfolder); $f++)
                if (strpos(strtolower($thisfolder[$f]), ".jpg"))
                $photos[]=$files[$x]."/".$thisfolder[$f];
                }
        }
$rand=rand(0, count($photos)); ?>
<img src="includes/crop.php?src=<?php echo $photos[$rand];?>&h=115&w=650&q=90" title="<?php echo $photos[$rand];?>" />

再次提前感谢:)约翰

4

2 回答 2

2

换行

$rand=rand(0, count($photos))

$rand=rand(0, count($photos)-1)

您是否使用 rand 来选择随机图像,但您必须将值限制在 [0, count($photos)-1] 区间内,否则可能会发生索引溢出。该错误会影响您的代码,但如果目录仅包含图像,则问题非常明显。

count($photo)等于 1 并且数组只包含一个索引为 0 的元素。

$rand=rand(0, count($photos)) => $rand=rand(0,1) => $rand 可以假设两个不同的值:0 或 1。在第一种情况下,一切都按预期工作。在后者中,错误将出现。

参考资料: http ://www.php.net/rand

附录

回应评论:代码在空目录的情况下非常有效,因为执行将跳过外部 for 语句。您可以使用 if 跳过所有代码,但效率增益将可以忽略不计。

.............

$str = strtolower($articleTitle); 

$files= scandir("images/gallery/".$str."/");
if (count($files)) {
    $photos = array();
        for ($x=0; $x<count($files); $x++){
        $files[$x]="images/gallery/".$str."/".$files[$x];
            if (is_dir($files[$x])){
                $thisfolder=scandir($files[$x]);
                for ($f=0; $f<count($thisfolder); $f++)
                if (strpos(strtolower($thisfolder[$f]), ".jpg"))
                    $photos[]=$files[$x]."/".$thisfolder[$f];
            }
        }
    $rand=rand(0, count($photos)-1);
    echo '<img src="includes/crop.php?src=' . $photos[$rand] 
       . '&h=115&w=650&q=90" title="'$photos[$rand]" />';
}

不过,我会使用不同的方法,如下所示:

$dirName = strtolower($articleTitle);
$oldDir = cwd();
chdir('images/gallery/'.$dirName);
$photos = glob('*.jpg');
$foreach(glob('*',GLOB_ONLYDIR) as $subdir) {
    $photos = array_merge($photos, glob($subdir.'/*.jpg'));
}
if (count($photos)) {
    $rand=rand(0, count($photos)-1);
    echo '<img src="includes/crop.php?src=' . $photos[$rand] 
         . '&h=115&w=650&q=90" title="'$photos[$rand]" />';
}
chdir($oldDir);
于 2012-03-15T11:24:53.070 回答
0

您可以尝试使用简单的代码

$files= scandir("images/"); $photos = ""; for ($x=0; $x < count($files); $x++){< if (strpos(strtolower($files[$x]), ".jpg")){ $photos = "images/".$files[$x]; break; } } ?> <img src="<?php echo $photos;?>" title="<?php echo $photos;?>" />

于 2012-03-15T11:34:28.133 回答