div 每 6 个结果 PHP MYSQL

div's with each 6 results in it PHP MYSQL

<div>
<?php   if ($result->num_rows > 0) { 
$i=1;
while($row = $result->fetch_assoc()) { 

        if( $i % 6 == 0 )
        { ?>        
            </div>
            <div>
    <?php } ?>
    <h4><?php echo $row["city"] ?></h4>
    <h6><?php echo $row["info"] ?></h6>
<?php   $i++;
}
} else {
echo "0 results";
}
?>
</div>

目标:div,其中每个 6 行。 当我使用 $i=1 时,第一个得到 5 结果,其他得到 6。 当我使用 $i=0 时,第一个是空的,其他的是 6.

如何得到第一个 div 也填充了 6 个结果?

您可以尝试设置 $i = 0,然后使用

if 语句中排除它
if ($i > 0 && $i % 6 == 0) 

因为 0 % 6 == 0。

尝试使用 array_chunk。这样你就不必担心把你的 div 放在哪里而且它更具可读性:

$rows = [];
while ($row = $result->fetch_assoc()) {
    $rows[] = $row;
}

foreach (array_chunk($rows, 6) as $subset) {
    echo "<div>";
    foreach ($subset as $row) {
        echo "<h4>{$row["city"]}</h4>"
        echo "<h6>{$row["info"]}</h6>"
    }
    echo "</div>";
}

使用@Justinas 提议的array_chunk 是重构代码的好方法。然而,使用您的原始代码,问题在于您检查打印数量的位置。首先检查输出量是错误的,因为它破坏了第一次迭代的逻辑。请参考下面的代码。

<div>
<?php

if ($result->num_rows > 0) { 
    $i = 1;
    while ($row = $result->fetch_assoc()) {
        # if ($i % 6 == 0) {     
        #     echo '</div><div>';
        # }
        # move commented code from above to ...

        echo "<h4>{$row["city"]}</h4>";
        echo "<h6>{$row["info"]}</h6>";

        # ... here
        if ($i % 6 == 0) {     
            echo '</div><div>';
        }

        $i++;
    }
} else {
    echo "0 results";
}
?>
</div>