【问题标题】:How can i get the quantity of every product outside of my while loop如何在我的 while 循环之外获取每种产品的数量
【发布时间】:2019-11-05 17:19:37
【问题描述】:

我正在从数据库中获取数据、id、名称和价格。但是在while循环里面也是一个量。我不知道如何掌握每种产品的数量。数量与 while 循环内的新产品重复。但是,如果我想捕获 while 循环之外的所有产品的数量,我只会得到一个值。我希望有人可以通过帖子给我答案(我是初学者)。

代码来了

  $arr = array();
  while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
      extract($row);
          $arr[] = $row;


      $_SESSION['cart-checkout'] = $arr;

      $quantity=$_SESSION['cart'][$id]['quantity'];


      $sub_total=$price*$quantity;


      echo "<div class='cart-row'>";
          echo "<div class='col-md-8'>";

              echo "<div class='product-name m-b-10px'><h4>{$name}</h4> 
             </div>";
              echo $quantity>1 ? "<div>{$quantity} items</div>" : "<div> 
              {$quantity} item</div>";

          echo "</div>";

          echo "<div class='col-md-4'>";
              echo "<h4>&#36;" . number_format($price, 2, '.', ',') . " 
              </h4>";
          echo "</div>";
      echo "</div>";

      $item_count += $quantity;
      $total+=$sub_total;

  }

【问题讨论】:

    标签: php arrays pdo while-loop


    【解决方案1】:

    你已经成功了一半。您正在增加内部循环,但要获得总数,您需要打印出外部循环。你还需要在开头声明变量total。

    试试这个:

      $arr = array();
      $total = 0; //declare variable
      while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
          extract($row);
              $arr[] = $row;
    
    
          $_SESSION['cart-checkout'] = $arr;
    
          $quantity=$_SESSION['cart'][$id]['quantity'];
    
    
          $sub_total=$price*$quantity;
    
    
          echo "<div class='cart-row'>";
              echo "<div class='col-md-8'>";
    
                  echo "<div class='product-name m-b-10px'><h4>{$name}</h4> 
                 </div>";
                  echo $quantity>1 ? "<div>{$quantity} items</div>" : "<div> 
                  {$quantity} item</div>";
    
              echo "</div>";
    
              echo "<div class='col-md-4'>";
                  echo "<h4>&#36;" . number_format($price, 2, '.', ',') . " 
                  </h4>";
              echo "</div>";
          echo "</div>";
    
          $item_count += $quantity;
          $total+=$sub_total;//increment inside loop
    
      }
    echo $total;//print outside loop
    

    【讨论】:

    • 您好,感谢您的宝贵时间。但我需要让数量在循环之外工作。我以为我可以将 $total 替换为 $quantity 并且它会起作用。但我仍然得到一种产品的输出,而不是所有产品的输出。所以我想要while循环中每个产品的数量并在while循环之外回显它
    • 我终于让它工作了,我确实在 while 循环上方添加了$quantity_all= '';。然后在while循环中我这样做了$quantity_all .=$quantity;,在while循环之后回显$quantity_all
    猜你喜欢
    • 2012-06-01
    • 1970-01-01
    • 2015-12-26
    • 2020-08-16
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    • 2015-05-02
    相关资源
    最近更新 更多