displaying table with images with PHP
I need to generate a table with php, that will display the images - names stored on database. It has to display 3 images in a row. The images are added 开发者_如何学JAVAto the database all the time, so I need that to be automatically generated, instead of hard coding the tables. I am not sure how do I do that? Please help!
You need to cycle the result recordset and print out the new row every 3rd element.
For example:
<table>
<tr>
<?php $i=0; foreach ($images as $image): ?>
<td><?php echo $image['name'] ?> <img src="<?php echo $image['path'] ?>" /></td>
<?php if(++$i%3==0): ?>
</tr><tr>
<?php endif ?>
<?php endforeach ?>
</tr>
</table>
suppose u get the all images name from database in an array
$img_array = array(
1=>'f.jpg',
2=>'s.jpg',
3=>'t.jpg',
4=>'f.jpg',
5=>'e.jpg'
);
// now create dynamic table via php
<table border="1" cellpadding="2" cellspacing="2" width="100%">
<tr>
<?php
$i=0;
foreach($img_array as $k){
if($i%3==0) { ?> </tr><tr> <?php } ?>
<td><img src="<?php echo $k?>" border="0"></td>
<?php $i++; } ?>
</tr>
</table>
Note: please write full path of image in src
before <?php echo $k?>
Iterate the image records, using modulo 3 to change to the next table row.
Something like:
echo '<table><tr>';
foreach ($images) {
echo '<td>$image</td>';
if ($i % 3 == 0) {
echo '</tr><tr>';
}
}
echo '</tr></table>';
A simple table like that would be like
<table>
<tr><td>1</td><td>2</td><td>3</td></tr>
<tr><td>1</td><td>2</td><td>3</td></tr>
</table>
To generate this automatically you need to store where you are in the table, first col, 2nd col or 3th col.
<?php
$pos = 1;
print "<table>"
for ($i=0; $i<=10;$i++)
{
if ($pos==1)
{
print "<tr><td>1</td>";
$pos=2;
}
else if ($pos==2)
{
print "<td>2</td>";
$pos=3;
}
else if ($pos==3)
{
print "<td>3</td></tr>";
$pos=1;
}
}
if ($pos==2 || $pos==3)
print "</tr>";
print "</table>"
Keep in mind that if you use the options with $i%3 from the other comments, that your table will start end/or finish with an empty row. This would need additional checks. The $i%3 will give the remainder of the division of $i and 3. So when $i/3 == 0, means it is true on every third row.
精彩评论