doudou3716 2013-11-13 01:26 采纳率: 100%
浏览 32

我需要将这个mysql_fetch_assoc数组输出到一个每行最多5列的表。

I have this table:

img id  | img_path   | listing_assoc_id|
----------------------------------------
   11   |img/img1.jpg |       12        |
   12   |img/img2.jpg |       12        |
   13   |img/img3.jpg |       12        |
   14   |img/img4.jpg |       12        | 
   15   |img/img5.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        |

And I want to display it into a table in html like this maximum of 5 images per row. I have been fiddling with different loops in combination of different loops like above for a couple hours but haven't found one that works like I need. They are either displaying the same images across the entire row or are messed up in some other way. Obviously need to use tr & td elements to format table correctly.

What I need:

     <tr>
     <td>img1</td> <td>img2</td> <td>img3</td> <td>img4</td> <td>img5</td>
     </tr>
     <tr>
     <td>img6</td> <td>img7</td> <td>img8</td> <td>img9</td> <td>img10</td>
     </tr>
     <tr>
     <td>img11</td> 
     </tr>
Some of the code that doesn't work:
$query = "SELECT * FROM listings_gallery WHERE listing_assoc_id = " 12 " ORDER BY img_id ASC";
    $image_set = mysqli_query($connection, $query);
    echo '<tr>';
        while($img = mysqli_fetch_assoc($image_set)){
            while($img['img_id'] < 5){
            echo "<td><img src='" . $img['img_path'] . "'></td>";
            }
            echo '<tr>'; 
     }

  • 写回答

2条回答 默认 最新

  • duanbei3704 2013-11-13 01:31
    关注

    I wouldn't actually depend on the image ID. You could use % 5 to do this, but the IDs may be out of order, etc. Instead, you can just fetch everything into an array and use 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>";
    }
    

    This is probably about as simple as it gets but it's not as memory efficient as could be. You could also maintain your own counter and check % 5 for that to break out of the inner loop.

    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示