显示X元素后插入新的表格行

时间:2016-04-06 15:57:50

标签: php html mysql arrays

我有一个包含许多不同图像的URL的数组。

我的目标是输出数组中的前七个图像,创建一个新行,输出接下来的7个图像,创建一个新行,然后继续这样做,直到阵列中没有剩下的URL。

当前代码

<?php
            $command = 'select * from products;';//The command to be executed
            $result = mysqli_query($con, $command); //The result of the command
            if (mysqli_num_rows($result) > 0) 
                {
                    // output data of each row
                    echo "<table align='center'>";
                    $images = array();
                    $name = array();
                    while($row = mysqli_fetch_assoc($result)) //Store all product images and their names in two SEPERATE arrays
                        {
                            $images[] = $row['Image'];
                            $names[] = $row['Name'];
                        }
                    for($x = 0; $x < 1; $x++)
                        {
                        echo "<tr>";
                        foreach($images as $image)
                            {
                                echo "<td> <img src='" . $image . "' height='80' width='100'/></td>";
                            }
                        echo "</tr>";
                    }   
                }
        ?>

目前,此代码水平输出$images[]数组内的所有图像,但在显示前七个图像后不会创建新行。

我将图像放在一张桌子内,以便输出均匀分布。

有人能指出我正确的方向,以获得我想要的输出吗?我环顾四周并尝试了几种解决方案,但我没有进一步前进。

2 个答案:

答案 0 :(得分:1)

使用以下代码行:

我没有桌子,因为我没有看到桌子的任何优势。如果您想清楚明了,请使用CSS

<?php
$command = "SELECT * FROM `products`";
$result = mysqli_query($con, $command); 
if(mysqli_num_rows($result) > 0){
  $i = 1;
  while($row = mysqli_fetch_object($result)){
  if($i++ > 6) echo "<br/>";?>
    <img src="<?php echo $row->Image;?>" height='80' width='100'/>
  <?php }   
}
?>

答案 1 :(得分:0)

您可以使用变量存储每行所需的项目数,并在关闭该行之前检查您是否达到此数字:

$nbImagesPerRow = 7;

获得了多少张图片:

$nbImages = mysqli_num_rows($result);

实施两个变量,一个检查当前行,另一个检查表结束时间:

$currentRowImageIndex = 1;
$totalImageIndex = 1;

然后,当你循环时,你检查是否必须打开或关闭一个新行:

while($row = mysqli_fetch_assoc($result)) {
    if (1 === $currentRowImageIndex) {
        echo '<tr>';
    }
    ...

    if (
        $currentRowImageIndex >= $nbImagesPerRow
        || $totalImageIndex >= $nbImages) {
        $currentRowImageIndex = 1;
        // you also should deal with the last line colspan when $totalImageIndex >= $nbImages)
        echo '<tr>';
    } else {
        $currentRowImageIndex++;
    }
$totalImageIndex++;

不要犹豫,使用一个html网格系统,如Bootstraps'或基础'(更多存在),允许你在div中水平对齐元素并适应用户屏幕。

相关问题