2013-02-25 101 views
0

我有这样的脚本:PHP图片显示

<?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”行。

+1

我觉得你并不需要'而($图像)' – fedorqui 2013-02-25 15:51:23

回答

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>"; 
?> 
+0

我尝试这样做,但它会显示所有的人都在一列,一列没有3。 – Sergiu 2013-02-25 15:54:03

+0

@sergiu因为你没有把你的代码包装在括号中,所以'foreach'只适用于第一行,'$ count'永远不会增加。 – 2013-02-25 15:55:35

+0

准确。 @Sergiu,我已经清理了一些代码,所以一切都更有意义。有时我们的身份代码的方式有很多帮助! – fedorqui 2013-02-25 16:01:17

0

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

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

否则,它只是循环代码的下一直线。

+0

如果我把如果($图像)它会显示在一行上的所有图片,而不是连续3如何它应该是。 – Sergiu 2013-02-25 15:56:32

+0

@sergiu看到我更新的答案 – 2013-02-25 15:57:35

0

您似乎在while上的逻辑非常糟糕。你在说while $image exists执行以下操作。那么$image不会改变,这将导致while永远继续。当脚本到达max_execution_time时最可能发生。

您目前的代码被设计为重复图像。如果您不希望这样做,则必须删除foreach中的while循环。

另请注意,由于您没有大括号,因此只有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>";