在显示X个元素后插入新行


Insert new table row after displaying X elements

我有一个数组,其中包含许多不同图像的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[]阵列内的所有图像,但在显示前七个图像后不创建新行。

我把图像放在一张桌子里,这样输出的图像就均匀地隔开了。

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

使用这行代码:

我没有桌子,因为我看不出这张桌子有什么好处。如果你想让事情变得清楚,那么就用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 }   
}
?>

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

$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或foundations(还有更多),它允许您在div中水平对齐元素并适应用户屏幕。