2013-03-16 95 views
0

當物品添加到購物車時,應該顯示該物品的物品ID和數量。在這種情況下,只會從會話中解析數量。物品ID未顯示。另外,當添加不同的物品時,購物車應該顯示另一個具有單獨數量的物品。PHP - 購物車,會話問題

<?php 
session_start(); 


?> 
<?php 
if (isset($_POST['pid'])) { 
    $pid = $_POST['pid']; 
    $wasFound = false; 
    $i = 0; 

    if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){ 
     $_SESSION["cart_array"] = array(1 => array("item_id" => $pid, "quantity" => 1)); 
    } else { 
     foreach ($_SESSION["cart_array"] as $each_item) { 
      $i++; 
      while (list($key, $value) = each($each_item)) { 
       if ($key == "item_id" && $value == $pid) { 
       array_splice($_SESSION["cart_array"], $i-1, 1,array(array("item_id" => $pid, "quantity" => $each_item['quantity'] + 1))); 
       $wasFound = true; 
       } 
      } 
     } 
     if ($wasFound == false) { 
     array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" => 1)); 
    } 
    } 
} 
?> 
<?php 
if (isset($_GET['cmd']) && $_GET['cmd'] == "emptycart") { 
    unset($_SESSION["cart_array"]); 
} 
?> 
<?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>"; 
     while (list($key, $value) = each ($each_item)) { 
      $cartOutput .= "key:$value<br />"; 
     } 
    } 
} 
?> 

有什麼建議嗎? 謝謝

回答

0

這是一些非常奇怪的數組操作,你在那裏。你應該能夠做到你需要一個foreach循環的一切:

foreach ($_SESSION["cart_array"] as $item_key => $each_item) { 
     if ($each_item['item_id'] == $pid) 
     { 
      $_SESSION["cart_array"][$item_key]['quantity']++; 
     } 
     $wasFound = true; 
    } 

如果這不是你熟悉的,foreach ($foo as $key => $value)是做什麼你都寫成while(list($key, $value) = each($foo))$foo++是短手$foo = $foo + 1的正常方式。

如果您將產品ID用作購物車陣列的鍵,則實際上可以使其更加簡單;這樣,你可以問問PHP是否存在密鑰,如下所示:

if (array_key_exists($pid, $_SESSION['cart_array'])) 
{ 
    $_SESSION['cart_array'][$pid]['quantity']++; 
} 
else 
{ 
    $_SESSION['cart_array'][$pid] = array('item_id' => $pid, 'quantity' => 1); 
}