php - foreach 在 while 循环中返回重复数据
问题描述
上下文:我有一个订购单,它有一个 html 选择和一个数字输入。因此用户选择该项目并输入他们想要的该项目的数量,这些将作为数组发送到处理程序页面。$_POST['item'];
是我想从数据库中选择产品信息的 id 数组。$amount = $_POST['amount'];
只是每个项目数量的数组。
问题:每一行都被行数复制,所以在这种情况下,它返回三行,但每行复制三次。
目标:我要做的就是 foreach$_POST['item']
从数据库中获取该行数据并在表格中显示它们以及相应的金额,以便用户可以确认订单。
句柄.php
<?php
$item = $_POST['item']; // array of product ids to select data from db
$amount = $_POST['amount']; // array of amounts of each product the user ordered
$note = $_POST['note'];
$i = 0;
$each = implode(',',$item);
$stmt = $dbh->query('SELECT *
FROM `products`
WHERE `id` IN (' . $each . ')');
<table class="table">
<thead>
<tr>
<th scope="col">Item</th>
<th scope="col">Quantity</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody>
<?php
while ($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
$product_id = $row['id'];
$product_name = $row['name'];
$product_price = $row['price'];
$row['quantity'] = $amount[$row['id']];
print "<pre>";
print_r($row);
print "</pre>";
?>
<tr>
<td><?php echo $product_name;?></td>
<td><?php echo $row['quantity'];?></td>
<td><?php echo $product_price;?></td>
</tr>
<?php } ?>
</tbody>
</table>
解决方案
我不确定您要做什么,但是您正在重新分配
$key = array() ;
在你之后立即
foreach ($amount as $key)
这导致你的
<td><?php echo $key;?></td>
尝试回显数组,因为您覆盖了 foreach 分配的 $key 的值。
您的帖子没有详细说明哪些数据被重复,所以我无法在这个答案中真正解决这个问题。
您正在复制相同的三行,因为您正在设置
$new = array_combine($item, $amount);
然后你的 SQL 正在抓取行
$stmt = $dbh->query('SELECT *
FROM `products`
WHERE `id` IN (' . $each . ')');
然后你循环使用相同的项目
foreach ($new as $key => $val) {
如果你想显示你在 SQL 中找到的项目,那么你不应该有
foreach ($new as $key => $val) {
在你的 while() 循环内。您的 while() 已经在为这些项目返回的行上循环。这假设您每个项目编号只有一个产品。
如果您希望为每个项目编号返回一个或多个“产品”,那么您应该在循环 foreach($new) 时执行 SQL,但这似乎不是代码的顶部正在执行的操作。
经过一番反复,我们发现了问题:金额需要与项目编号联系起来。
您从 HTML 中以数组形式获取项目编号和数量。因此,您需要遍历这些项目并将它们与您的数量相关联。
// where your qualities will live
$quantities = array() ;
// loop through the array of items you received and match them up with their quantity
foreach($item as $k=>$id) {
$quantities[$id] = $amount[$k] ;
}
然后,您可以使用以下方法访问 while 循环中的数量:
$row['quantity'] = $quantities[$row['id']] ;
推荐阅读
- r - 您可以将数据传输到pairwise.t.test 中吗?
- wpf - Caliburn.Micro:如何将 Conductor.Collection.AllActive 的特定项绑定到 ContentControl
- python - Sqlite可以处理多少用户,Django
- c# - IIS Express 与 dotnet 运行
- swift - 如何在 Swift5 中监听 keydown 事件?
- django - 我无法访问 Django 管理站点
- c# - 无法在 C#/WPF 类库中使用 XAML ResourceDictionary
- excel - 如果 B 列中有值,则复制 A 列中的值,从 E7 Excel 开始粘贴
- c++ - 在c ++中的模板实例化中使用带有构造函数的类作为类型参数
- javascript - JavaScript:从对象的左右键中修剪空格