2011-04-08 119 views
1

在我的地盤我有幾百行代碼的,就像這樣:PHP循環問題

<a href="highslide/images/large/08/02IMG_0012.jpg" class="highslide" 
      onclick="return hs.expand(this, config1)"> 
    </a> 
    <a href="highslide/images/large/08/03IMG_0020.jpg" class="highslide" 
      onclick="return hs.expand(this, config1)"> 
    </a> 
    <a href="highslide/images/large/08/04IMG_0019.jpg" class="highslide" 
      onclick="return hs.expand(this, config1)"> 
    </a> 
    <a href="highslide/images/large/08/05IMG_0011.jpg" class="highslide" 
      onclick="return hs.expand(this, config1)"> 
    </a> 

我想知道,如果它可以使用PHP來拯救我有代碼的那麼多行。使用批量重命名器將照片文件名更改爲photo1.jpg,photo2.jpg等。我只是不確定如何實現PHP的原因,我是一個小菜鳥。我得到了這樣的somin到目前爲止:

$photo = 1; 
$ext = .jpg; 

while() { 

echo '<a href="highslide/images/large/08/'.$photo.$ext.'" class="highslide" onclick="return hs.expand(this, config1)">'; 

$photo++ 

} 
+0

答案這裏是正確的,但有另一種方法:通過將圖像存儲在目錄中的內容循環。 (見:http://php.net/manual/en/function.readdir.php)。這種方法將阻止您每次上傳圖像時都必須編輯PHP文件,並且可以處理任意文件名。 – horatio 2011-04-08 15:45:10

回答

1

雖然「while」循環會執行此操作,但「for」循環更適合順序迭代。

$photoCount = 10; 
$ext = .jpg; 

for ($i = 1; $i <= $photoCount; $i++) { 
    echo '<a href="highslide/images/large/08/'.$i.$ext.'" class="highslide" onclick="return hs.expand(this, config1)">'; 
} 
+0

這可能是更好的解決方案。 – Shoe 2011-04-08 15:18:56

2

你幾乎在那裏,你只需要在你的while循環添加一個退出條件。 當循環結束?當它打印完所有的照片。因此,只需添加一個變量保存的照片數量和while條件檢查:

$photo = 1; 
$ext = '.jpg'; 
$numberOfPhotos = 100; 

while($photo <= $numberOfPhotos) { 

    echo '<a href="highslide/images/large/08/'.$photo.$ext.'" class="highslide" onclick="return hs.expand(this, config1)">'; 

    $photo++; 

} 
+0

你有一個錯字:'$ ext = .jpg;'必須是'$ ext ='.jpg';'。 – Shoe 2011-04-08 15:16:38

+0

你是對的,我只是複製了問題代碼而沒有檢查它:) – 2011-04-08 15:17:23

2

重縮寫代碼:

$pics = array("001","002",etc..); 

foreach ($pics as $pic) 
{ 
    echo '<a...' . $pic . '..>'; 
} 

這應該證明參與的原則;適應您的需求。

0

您使用的結構幾乎是正確的。你只需添加一種方法來停止你使用的while()循環。 while循環將循環直到其括號內的條件爲假。 像Davide一樣。他用最大數量來停止循環。

0
<?php 

$total_photo = 20; // set total number of photo 
$photo_url = "highslide/images/large/08/photo"; // set the default photo url 
$photo_ext = ".jpg"; 

for($i = 1; $i <= $total_photo; $i++): 
?> 

<a href="<?php echo $photo_url . $i . $photo_ext; ?>" class="highslide" onclick="return hs.expand(this, config1)"> 
Photo <?php echo $i; ?> 
</a> 

<?php endfor; ?> 

它的更好,如果你只是內聯的PHP代碼爲HTML,以便它更易讀