开发者

PHP loop problem

开发者 https://www.devze.com 2023-02-22 21:14 出处:网络
On my site I have hundreds of lines of code just like this: <a href=\"highslide/images/large/08/02IMG_0012.jpg\" class=\"highslide\"

On my site I have hundreds of lines of code just like this:

<a href="highslide/images/large/08/02IMG_0012.jpg" class="highslide" 
            onclick="return hs.expand(this, config1 )开发者_Python百科">
    </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>

I was wondering if its possible to use PHP to save me having so many lines of code. Changing the photos filenames to photo1.jpg, photo2.jpg etc would be easy with a batch renamer. I'm just unsure how to implement the PHP cause I'm a bit of a noob. I got somin like this so far:

$photo = 1;
$ext = .jpg;

while() {

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

$photo++

}


Heavily abbreviated code:

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

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

This should demonstrate the principle involved; adapt it to your needs.


You are almost there, you just need to add an exit condition in your while loop. When the loop has to end? When it has printed all the photos. So, just add a variable holding the number of photos and check in the while condition:

$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++;

}


Although "while" loops will do this, "for" loops are more appropriate for sequential iteration.

$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 )">';
}


The structure you use is almost correct. You just have to add a way to stop the while() loop you use. The while loop will loop until the condition within his parentheses is false. Like Davide did. He used a maximum number to stop the loop.


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

Its better if you just inline the php code to html so that its more readable

0

精彩评论

暂无评论...
验证码 换一张
取 消