foreach inside while while循环返回重复数据

时间:2018-06-03 19:15:19

标签: php mysql foreach

上下文:我有一个订购表单,它有一个html选择和一个数字输入。因此,用户选择该项目并输入他们想要该项目的金额,这些项目将作为数组发送到手册页面。 $_POST['item'];是一个id的数组,我想从数据库中选择产品信息。 $amount = $_POST['amount'];只是每个项目数量的数组。

问题:每行都按行数复制,所以在这种情况下,它返回三行,但每次重复三次。

目标:我要做的就是foreach $_POST['item']从数据库中获取行数据并在表格中显示它们和相应的金额,以便用户确认订购。

handle.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>

1 个答案:

答案 0 :(得分:1)

我不确定你要做什么,但你要重新分配

$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()已经循环遍历为这些项返回的行。这假设您每个商品编号只有一个产品。

如果您期望一个或更多&#39;产品&#39;要为每个项目编号返回,那么您应该在循环遍历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']] ;