2013-02-25 100 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>";