【问题标题】:Insert new table row after displaying X elements显示 X 元素后插入新表格行
【发布时间】:2016-04-07 00:30:26
【问题描述】:

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

我的目标是输出数组中的前 7 个图像,创建一个新行,输出接下来的 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[] 数组中的所有图像,但在显示前七张图像后不会创建新行。

我将图像放在一个表格中,以便输出均匀分布。

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

【问题讨论】:

  • 我可以破坏你的代码来构建新代码吗?
  • @FrayneKonok 当然。
  • 查看答案。

标签: php html mysql arrays


【解决方案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 }   
}
?>

【讨论】:

    【解决方案2】:

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

    $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 中水平对齐元素并适应用户屏幕。

    【讨论】:

      猜你喜欢
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-15
      • 1970-01-01
      相关资源
      最近更新 更多