购物车只显示一个项目

时间:2014-02-14 00:11:14

标签: php shopping-cart

我想显示产品列表,但在输出浏览器中,此代码仅显示最后一个产品并忽略之前的项目:

<?php 
  $cartOutput="";
  if(!isset($_SESSION["cart_array"])|| count($_SESSION["cart_array"])<1){
$cartOutput="<h2 align='center'>Your shopping cart is empty</h2>";
  }else{
$i=0;
foreach($_SESSION["cart_array"] as $each_item){
    $i++;
    $cartOutput="<h2>Cart Item $i</h2>";
        $cartOutput="Item ID:" .$each_item['item_id']."<br>";
    $cartOutput="Item Quantity:" .$each_item['item_id']."<br>";
    //while(list($key,$value)=each($each_item)){
      //$cartOutput="item_id: $pid <br> $key: $value<br/>";
    //}
       }
      }
      ?>

这里是html

  <body>
  <div align="center" id="mainWrapper">
  <?php include_once("template_header.php");?>
   <div id="pageContent">
   <div style="margin:24px; text-align:left;">
  <?php echo $cartOutput ?>
  <br /><br />
    <a href="cart.php?cmd=emptycart">Click Here to Empty Your Shopping Cart</a>
    </div>
    <br />
    </div>
    <?php include_once("template_footer.php");?>
   </div>
   </body>
  </html>

2 个答案:

答案 0 :(得分:1)

每次while语句进行迭代时,您都会重置cartOutput值。 所以在迭代内部将$ cartOutput =“....”更改为$ cartOutput。=“....”

<?php 
$cartOutput="";
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
    $cartOutput="<h2 align='center'>Your shopping cart is empty</h2>";
} else {
    $i=0;
    foreach($_SESSION["cart_array"] as $each_item) {
        $i++;
        $cartOutput .= "<h2>Cart Item $i</h2>";
        $cartOutput .= "Item ID:" .$each_item['item_id']."<br>";
        $cartOutput .= "Item Quantity:" .$each_item['item_id']."<br>";
     }
}
?>

答案 1 :(得分:1)

这是因为每次foreach循环运行时都会覆盖变量$ cartOutput。这意味着只有购物车的最后一个元素可见。您可以通过附加到$ cartOutput或将其作为数组并在之后插入它来解决此问题。

像这样(使用内爆):

<?php 
$cartOutput=array();
if(!isset($_SESSION["cart_array"])|| count($_SESSION["cart_array"])<1){
    $cartOutput="<h2 align='center'>Your shopping cart is empty</h2>";
}else{
    $i=0;
    foreach($_SESSION["cart_array"] as $each_item){
        $i++;
        $cartOutput[] = "<h2>Cart Item $i</h2>";
        $cartOutput[] = "Item ID:" .$each_item['item_id']."<br>";
        $cartOutput[] ="Item Quantity:" .$each_item['item_id']."<br>";
    }
    $cartOutput = implode('<br />', $cartOutput);
}
?>

或者您也可以将所有输出附加到$ cartOutput中已经存在的输出中,如下所示:

<?php 
$cartOutput="";
if(!isset($_SESSION["cart_array"])|| count($_SESSION["cart_array"])<1){
    $cartOutput="<h2 align='center'>Your shopping cart is empty</h2>";
}else{
    $i=0;
    foreach($_SESSION["cart_array"] as $each_item){
        $i++;
        // note the use of .= which is a combined assignment and concatenation operators (it concatenates all content after the .= to the string preceding it)
        $cartOutput .= "<h2>Cart Item $i</h2>";
        $cartOutput .= "Item ID:" .$each_item['item_id']."<br>";
        $cartOutput .="Item Quantity:" .$each_item['item_id']."<br>";
    }
}
?>