Reputation: 11
I have a slideshow with jQuery Cycle Plugin from Malsup and I don't know php at all.
I want to have a dynamically generated slideshow on my website.
Here's the markup:
<div id="slideshow">
<div class="slide">
<a href="image1.jpg"><img src="image1-thumb.jpg" title="image1"/></a>
<a href="image2.jpg"><img src="image2-thumb.jpg" title="image2"/></a>
<a href="image3.jpg"><img src="image3-thumb.jpg" title="image2"/></a>
</div>
<div class="slide">
<a href="image4.jpg"><img src="image1-thumb.jpg" title="image1"/></a>
<a href="image5.jpg"><img src="image2-thumb.jpg" title="image2"/></a>
<a href="image6.jpg"><img src="image3-thumb.jpg" title="image2"/></a>
</div>
</div>
The problem is that image1 is static, while the other 5 images are fetched dynamically in php:
<?php foreach ($images as $image) { ?>
<a href="<?php echo $image['popup']; ?>" title="<?php echo $heading_title; ?>"><img src="<?php echo $image['thumb_tiny']; ?>" alt="<?php echo $heading_title; ?>"/></a>
<?php } ?>
How can I wrap every three images in one div with .slide class with help of php, so that the first slide contains one static image plus two dynamin ones, and the other slides (infinite number) contain the next three dynamically fetched imaged?
Thank you and hope my description is not hard to get :)
Upvotes: 1
Views: 1003
Reputation: 7131
<div id="slideshow">
<?
$n_images = 3;
$i = 0;
while ($i < count($images)) {
?>
<p class="slide">
<?
if ($i == 0) {
?>
<a href="static.jpg" title="Static"><img src="static_thumb.jpg" alt="Static" /></a>
<?
}
for ($j = 0; $j < ($i > 0 ? $n_images : $n_images - 1); $j++) {
?>
<a href="<? echo $images[$i + $j]['popup']?>" title="<? echo $heading_title?>"><img src="<? echo $images[$i + $j]['thumb_tiny']?>" alt="<? echo $heading_title?>" /></a>
<?
}
?>
</p>
<?
$i += $n_images;
}
?>
</div>
Upvotes: -1
Reputation: 30996
The modulo operator is really handy in this kind of situation:
if (!empty($images)) {
echo '<div class="slide">';
for ($i = 0; $i < count($images); $i++) {
$image = $images[$i];
// check if we need to start a new div
if ($i > 0 && $i % 3 === 0) {
echo '</div><div class="slide">';
}
echo '<a href="'.$image['popup'].'" title="'.$heading_title.'"><img src="'.$image['thumb_tiny'].'" alt="'.$heading_title.'"/></a>';
}
echo '</div>';
}
Upvotes: 0
Reputation: 26574
Use a for loop so you have an index and then just check if the modulo 3 of that index is 0 to do something every three images.
<?php
for ($i = 0; $i < count($images); $i++)
{
if ($i % 3 == 0) { // Do something every 3 images }
echo "<a href=... // etc
}
?>
Since your first image is static, and this is the only special case, you can explicitly just check for that case and alter the values accordingly,
if ($i == 2) { // Force a div }
// You then need to offset the value for the modulo check,
if ($i > 2 && $i+2 % 3 == 0) { // Do something every 3 images after first 2 }
Upvotes: 3