我需要将此mysql_fetch_assoc数组输出到每行最多 5 列的表中


I need to output this mysql_fetch_assoc array to a table with maximum of 5 columns per row.

我有这个表:

图像标识 |img_path |listing_assoc_id|----------------------------------------   11 |图像/图像1.jpg |      12 |   12 |img/img2.jpg |      12 |   13 |img/img3.jpg |      12 |   14 |img/img4.jpg |      12 |   15 |图像/图像5.jpg |      12 |   16 |img/img6.jpg |      12 |   18 |img/img7.jpg |      12 |   21 |img/img8.jpg |      12 |   22 |img/img9.jpg |      12 |   23 |img/img10.jpg|      12 |   24 |img/img11.jpg|      12 |

我想以 html 格式将其显示到表格中像这样,每行最多 5 张图像。几个小时以来,我一直在摆弄不同的循环和上面的不同循环组合,但还没有找到我需要的。它们要么在整个行中显示相同的图像,要么以其他方式搞砸。显然需要使用tr和td元素来正确格式化表格。

我需要什么:

      
        img1
        img2
        img3
        img4
        img5
      
      
        img6
        img7
        img8
        img9
        img10
      
      
        img11
      
    
一些不起作用的代码:
$query = "从listings_gallery中选择 *,其中 listing_assoc_id = " 12 " 按 img_id ASC 排序";    $image_set = mysqli_query($connection, $query);    回声"";        while($img = mysqli_fetch_assoc($image_set)){            while($img['img_id'] <5){            echo "";            }            回声"";     }

我实际上并不依赖于图像ID。 您可以使用% 5来执行此操作,但 ID 可能顺序不正确,等等。 相反,您可以将所有内容提取到数组中并使用array_chunk

$img = array();
while ($img = mysqli_fetch_assoc($image_set)) {
    $imgs[] = $img;
}
foreach (array_chunk($imgs, 5) as $img_chunk) {
    echo "<tr>";
    foreach ($img_chunk as $img) {
        echo "<td>$img</td>";
    }
    echo "</tr>";
}

这可能很简单,但它的内存效率并不高。 您还可以维护自己的计数器并检查% 5以突破内部循环。

$images_rows = mysqli_query($connection, $query);
$images = array();
while ($image = mysqli_fetch_assoc($images_rows)) {
   $images[] = $image;
}
echo '<table><tr>';
$ct = 0;
$ctt = 0;
$size = sizeOf($images) - 1;
foreach($images as $image){
     if($ct == 5) {
       echo '<tr>';
       $ct = 0;
     }
     echo "<td><img src='" . $image['img_path'] . "'></td>"; 
     $ct++; 
     $ctt++;
     echo ($ct == 5 && $ctt != $size) ? '</tr>': '';
}
echo '</tr></table>'