How do I change this php while loop?
I am trying to display some images dynamically from a mysql table.
This is what I tried with PHP and it worked for me.
// Fetch all the records:
while ($stmt->fetch()) {
$html = " <div class='row-fluid custom'>\n";
$html .= " <div class='span6'>\n";
$html .= " <img src='images/{$image}'>\n";
$html .= " </div>\n";
$html .= " </div>\n";
//Add images to array
$images[] = $html;
}
And this is the markup on top of PHP:
<div class='row-fluid custom'>
<div class='span6'>
<img src='images/cond-1.png'>
</div>
</div>
<div class='row-fluid custom'>
<div class='span6'>
<img src='images/cond-2.png'>
</div>
</div>
<div class='row-fluid custom'>
<div class='span6'>
<img src='images/cond-3.png'>
</div>
</div>
<div class='row-fluid custom'>
<div class='span6'>
<img src='images/cond-4.png'>
</div>
</div>
But my problem is when I am going to change the above Markup as shown below.
<div class="row-fluid custom">
<div class="span6">
<img src="images/cond-1.png">
</div>
<div class="span6">
<img src="images/cond-2.png">
</div>
</div>
<div class="row-fluid custom">
<div class="span6">
<img src="images/cond-3.png">
</div>
<div class="span6">
<img src="images/cond-4.png">
</div>
</div>
Actually I need to group two images inside a row-fluid
DIV when displaying my images.
Can anyone tell me how I create such markup using php?
Hope someone can help me.
Thank.
source to share
You need to use a module function like in this example :
$images = array('foo.jpg', 'bar.jpg','baz.jpg','glorp.jpg');
$html = '';
for($i = 0; $i < count($images); $i++){
if($i % 2 == 0) {
$html .= " <div class='row-fluid custom'>\n";
$html .= " <div class='span6'>\n";
$html .= " <img src='images/{$images[$i]}'>\n";
$html .= " </div>\n";
} else {
$html .= " <div class='span6'>\n";
$html .= " <img src='images/{$images[$i]}'>\n";
$html .= " </div>\n";
$html .= " </div>\n";
}
}
echo $html;
By using modulus versus 2, you will be able to decide which output to add to the variable $html
. A result of 0 indicates that the number (string) is divisible by 2, which allows the start of the div to appear. Any other result allows the end of the div to be drawn.
source to share
Use while while
$i = 0;
while ($stmt->fetch()) {
$html = "";
if($i % 2 == 0) $html = " <div class='row-fluid custom'>\n";
$html .= " <div class='span6'>\n";
$html .= " <img src='images/{$image}'>\n";
$html .= " </div>\n";
if($i++ % 2 == 1) $html .= " </div>\n";
//Add images to array
$images[] = $html;
}
source to share
just add a condition for open / close div
:
$open_div=true;
while ($stmt->fetch()) {
if( $open_div )
$html = " <div class='row-fluid custom'>\n";
$html .= " <div class='span6'>\n";
$html .= " <img src='images/{$image}'>\n";
$html .= " </div>\n";
if( $open_div = !$open_div )
$html .= " </div>\n";
//Add images to array
$images[] = $html;
}
As a side note, your code introduces a lot white-spaces
that summarize the total page size and increase page load times.
source to share