假设我的服务器上有许多用户上传的图像。每张图片在数据库中也有一行,其中包含文件名、类别、文件大小、扩展名和位置等信息。
当我想要显示这些图像时,我使用了一个mysql_query和一个while循环。这是有效的,但图片都有不同的大小,它们显示在彼此的旁边或下面,这看起来真的很糟糕。
假设我有20张这样的图片,我如何才能显示5张图片,4行长?
发布于 2012-05-31 00:49:14
假设包含图像数据的对象的数字索引数组:
<div class="row">
<?php
// loop through all my images taking the index and image object
foreach( $images as $idx=>$image ) {
// If this isn't the 1st image & the modulus of 5 and $idx is 0, make a new row.
if( $idx > 0 && !(5%$idx) ) {
</div><div class="row">
}
// Print out the image
echo '<img src="' . $image->filename . '" />';
} ?>
</div>如果你用第一个数除以第二个数,模数基本上就是余数。因此,当我们打印了5个图像时,5/5=1,没有余数,所以我们创建了一个新行。
我相信这会产生类似这样的东西:
<div class="row">
<img src="img1.jpg" />
<img src="img2.jpg" />
<img src="img3.jpg" />
<img src="img4.jpg" />
<img src="img5.jpg" />
</div>
<div class="row">
<img src="img6.jpg" />
<img src="img7.jpg" />
<img src="img8.jpg" />
<img src="img9.jpg" />
<img src="img10.jpg" />
</div>然后可以使用CSS设置样式:
<style type="text/css">
div.row {
clear:left;
}
div.row img {
float:left;
}
</style>当涉及到调整图像大小时,您有两个选择:
编辑:作为对您的问题的回答,您需要这样做才能获得图像数组:
<?php
// Build an array of images
$sql = 'SELECT * FROM images';
$result = mysql_query( $sql );
while( $obj = mysql_fetch_object( $result ) ) {
$images[] = $obj;
}
?>发布于 2012-05-31 00:48:40
伪代码
$i = 0;
while($row = mysql_fetch_object($result) {
//displaying image
....
if($i % 4 == 0) {
echo '<BR>';
}
$i++;
}https://stackoverflow.com/questions/10820450
复制相似问题