php - 带有单独表格的 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>
解决方案
如果要使用单个循环解析结果,可以选择以下方法。这里的重要部分是您需要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"];
};
}
当然,您可以使用BundelName
as 键将结果集分组并存储在数组中,并使用另一个循环打印预期的输出:
$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>";
}
推荐阅读
- python - 具有张量流概率的真实 NVP
- php - 在 CakePHP 4.x 中禁用会话超时
- android - 如何在不丢失图像质量的情况下完美地将图像放入 imageview android
- python - 从橙色动态检测红色的阈值方法
- c - 您可以使用 struct XrmOptionDescRec 数组将非 Motif 相关参数传递给应用程序吗?
- reactjs - 如何在反应中使用上下文 api 将数据添加到其余 api?
- .net - 什么是捕获取消订阅事件的最佳方式
- c - 为什么我的 MingW-64 位编译的 64 位 Windows .EXE 在添加简单的字符串分配时会崩溃,而对于 32 位它可以正常工作?
- android - 如何在 Jetpack Compose 中管理 2D 网格 UI 的状态?
- amazon-web-services - 使用 POSTMan 调用 APIGateway 时不执行请求验证