0

我有这个脚本:

 <?php 
                $count = 0;
        foreach(glob("images/{*.gif,*.jpg,*.png,*.jpeg,*.bmp}", GLOB_BRACE) as $image)
        while ($image)
        {
            if($count==3)
            {
               print "</tr>";
               $count = 0;
            }
            if($count==0)
               print "<tr>";
               print "<td>";
            ?>
               <img src="<?php echo $image;?>" width="80" height="80"/>
                <?php
            $count++;
            print "</td>";
        }
        if($count>0)
           print "</tr>";
        ?>

它应该从文件夹中获取图像(在本例中为“图像”)并连续显示 3 张。但它显示一张图片 1000000 次。我能做些什么来解决这个问题?我试图修复它,我只知道问题出在“while”行。

4

3 回答 3

0

尝试删除线

while($image)

请注意,该行

foreach(glob("images/{*.gif,*.jpg,*.png,*.jpeg,*.bmp}", GLOB_BRACE) as $image)

已经沿着图像循环,当目录中没有更多图像时将完成。

我稍微清理了代码:

<?php 
    $count = 0;
    foreach(glob("images/{*.gif,*.jpg,*.png,*.jpeg,*.bmp}", GLOB_BRACE) as $image)
    {
        if($count==3)
        {
           print "</tr>";
           $count = 0;
        }
        if($count==0)
           print "<tr>";

        print "<td>";
        print "<img src=$image width=\"80\" height=\"80\"/>";
        print "</td>";
        $count++;
    }
    print "</tr>";
?>
于 2013-02-25T15:52:53.523 回答
0

问题是$image在while循环期间不会改变。因此,您在您的内部创建了一个无限循环,foreach因为$image继续评估为真。

while 循环在您的代码中是不必要的,可以删除。foreach您已经使用您的语句遍历图像。

确保将所有foreach逻辑包装在花括号中,如下所示:

foreach(glob("images/{*.gif,*.jpg,*.png,*.jpeg,*.bmp}", GLOB_BRACE) as $image)
{
    if($count==3)
    {
       print "</tr>";
       $count = 0;
    }
    if($count==0)
       print "<tr>";
       print "<td>";
    ?>
       <img src="<?php echo $image;?>" width="80" height="80"/>
    <?php
    $count++;
    print "</td>";
}
if($count>0)
   print "</tr>";

否则它只会循环下一行直接的代码。

于 2013-02-25T15:53:00.273 回答
0

你的逻辑似乎很糟糕while。您是说while $image exists执行以下操作。那么$image不会改变,这将导致while永远继续。当脚本到达max_execution_time.

您当前的代码旨在重复图像。如果您不想这样做,则必须while删除foreach.

另请注意,由于您没有大括号,因此只有while将在中执行,foreach并且该if语句将在完成后执行一次。如果不重复,请使用大括号foreach来确保一切都在您想要的时候运行。

像这样:

foreach(glob("images/{*.gif,*.jpg,*.png,*.jpeg,*.bmp}", GLOB_BRACE) as $image)
{
        if($count==3)
        {
           print "</tr>";
           $count = 0;
        }
        if($count==0)
           print "<tr>";
        print "<td>";
        ?>
        <img src="<?php echo $image;?>" width="80" height="80"/>
        <?php
        $count++;
        print "</td>";
}
if($count > 0)
    print "</tr>";
于 2013-02-25T15:54:42.243 回答