首页 > 解决方案 > 带有单独表格的 PHP 循环

问题描述

我如何使用不同的表来分割数据,我需要用循环显示我的所有数据,但列的“捆绑名称”将与一个表相同。

PHP代码:

<table>
<?php
include('connection.php');

$result1 = mysqli_query($conn, "SELECT * FROM bundel ");
while ($row = mysqli_fetch_assoc($result1)) {
    echo $row['BundelName'];
    $bundel = $row['BundelName'];

    echo '<tr>';
    echo '<td>';
    echo $row['SKU'];
    echo '</td>';
    echo '<td>';
    echo $row['Description'] ;
    echo '<td>';
    echo '</tr>';
    
    if ($row['BundelName'] != $bundel){
        echo"</table><br><br><table>";
    } 

}
?>
</table>

MySQL 我的结果

我的预期结果

标签: phphtml

解决方案


如果要使用单个循环解析结果,可以选择以下方法。这里的重要部分是您需要ORDER BY在语句中添加一个子句并在脚本中进行适当的更改,以使您的循环正常工作。

基于问题中的代码的简化示例:

$result1 = mysqli_query($conn, "SELECT * FROM bundel ORDER BY BundelName");
$bundel = "";
while ($row = mysqli_fetch_assoc($result1)) {
    if ($bundel != $row["BundelName"]) {
        echo "<table>";
        echo '<tr><td>' . $row['BundelName'] . '</td></tr>';
    };

    echo '<tr>';
    echo '<td>' . $row['Description'] . '</td>';
    echo '<td>' . $row['SalesPrice'] . '</td>';
    echo '</tr>';

    if ($bundel != $row["BundelName"]) {
        echo "</table>";
        $bundel = $row["BundelName"];
    };
}

当然,您可以使用BundelNameas 键将结果集分组并存储在数组中,并使用另一个循环打印预期的输出:

$stmt = mysqli_query($conn, "SELECT * FROM bundel");
$result = array();
while ($row = mysqli_fetch_assoc($stmt)) {
    $result[$row["BundleName"]][] = array(
        "Description" => $row["Description"],
        "SalePrice" => $row["SalePrice"]
    );  
}

foreach ($result as $bundel => $products) {
    echo "<table>"; 
    echo '<tr><td>' . $bundel . '</td></tr>';
    foreach ($products as $product) {
        echo '<tr>';
        echo '<td>' . $product["Description"] . '</td>';
        echo '<td>' . $product["SalePrice"] . '</td>';
        echo '</tr>';
    }
    echo"</table>";     
}   

推荐阅读