为什么我的ID没有显示在页面中

时间:2014-01-12 17:54:07

标签: php

我正在按照http://www.youtube.com/watch?v=WXqbQy9fOp8进行购物车教程。 我密切关注代码,但无法得到相同的结果。

我的商品ID和数量假设在我点击添加到购物车时显示,但是,仅显示我的数量。有人能告诉我我的代码有什么问题吗?

由于 这是我的编码..

<?php
if (isset($_POST['pid'])) {
    $pid = $_POST['pid'];
    $wasFound = false;
    $i = 0;
    // If the cart session variable is not set or cart array is empty
    if (!isset($_SESSION["supermarketcart"]) || count($_SESSION["supermarketcart"]) < 1) { 
        // RUN IF THE CART IS EMPTY OR NOT SET
        $_SESSION["supermarketcart"] = array(1 => array("id" => $pid, "quantity" => 1));
    } else {
        // RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
        foreach ($_SESSION["supermarketcart"] as $each_item) { 
              $i++;
              while (list($key, $value) = each($each_item)) {
                  if ($key == "id" && $value == $pid) {
                      // That item is in cart already so let's adjust its quantity using array_splice()
                      array_splice($_SESSION["supermarketcart"], $i-1, 1, array(array("id" => $pid, "quantity" => $each_item['quantity'] + 1)));
                      $wasFound = true;
                  } // close if condition
              } // close while loop
           } // close foreach loop
           if ($wasFound == false) {
               array_push($_SESSION["supermarketcart"], array("id" => $pid, "quantity" => 1));
           }
    }
    header("location: cart.php"); 
    exit();
}
?>
<?php
//if user choose to empty cart
if(isset($_GET['cmd']) && $_GET['cmd'] == "emptycart")
{
    unset($_SESSION["supermarketcart"]);
}
?>

<?php
//render the cart for user to view
$cartOutput = "";
if(!isset($_SESSION["supermarketcart"]) || count($_SESSION["supermarketcart"]) < 1 ){
    $cartOutput = "<h2 align = 'center'> Your shopping cart is empty</h2>";
}
else
{
    $i = 0;
    foreach ($_SESSION["supermarketcart"] as $each_item)
    {
        $i++;
        $cartOutput = "<h2>Cart Item $i</h2>";
        while(list($key,$value) = each($each_item))
        {
            $cartOutput ="$key:$value</br>";
        }
    }
}

?>

2 个答案:

答案 0 :(得分:0)

$cartOutput = "<h2>Cart Item $i</h2>";

$cartOutput = "$key:$value</br>"

问题出在这些方面。您正在循环的每一步重写cartOutput变量(从而清除'id')。 您应该添加数据:

$cartOutput .= "<h2>Cart Item $i</h2>";

$cartOutput .= "$key:$value"

答案 1 :(得分:0)

您需要在循环中追加cartOutput。你每次都重新分配了cartOutput。

尝试这样:

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