0

我一生都无法理解我是如何获得物品总量的。我一直在按照本教程建立一个网上商店。http://jameshamilton.eu/content/simple-php-shopping-cart-tutorial

一切似乎都在本教程中工作。但我需要将商品总数添加到我的购物车中。该代码正在创建一个具有 id 和数量编号的数组作为存储在 SESSION['cart'] 中的数组。我一直在搞乱 FOREACH 代码,但我只能得到购物车中一项的总数,即数组的总数。但我需要总数量的总和,而不是行的总和。

非常感谢您在正确方向上的任何帮助。

工作代码:

$product_id = $_GET[id];     //the product id from the URL 
$action     = $_GET[action]; //the action from the URL
if($product_id && !productExists($product_id)) {
   die("Error. Product Doesn't Exist");
}
switch($action) {   //decide what to do
case "add":
$_SESSION['cart'][$product_id]++; //add one to the quantity of the product with id $product_id 
break;
case "remove":
$_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id 
if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]);
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart. 
break;
}


if($_SESSION['cart']) { //if the cart isn't empty
//show the cart
echo "<table border='1' padding=\"3\" width=\"40%\">";
   foreach($_SESSION['cart'] as $product_id => $quantity) {
   $sql = sprintf("SELECT productName, productImg, price FROM products WHERE id = %d;", $product_id);
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) {
list($productName, $productImg, $price) = mysql_fetch_row($result);
$arrayquantity = is_array($_SESSION['cart']) ? count($_SESSION['cart']) : 0;
$line_cost = $price * $quantity;        //work out the line cost
$total = $total + $line_cost;           //add to the total cost
}else{
//you have no items
}
function productExists($product_id) {
$sql = sprintf("SELECT * FROM products WHERE id = %d;", $product_id); 
return mysql_num_rows(mysql_query($sql)) > 0;
}

我已经尝试了以下但它只是导致“0”

if(isset($_SESSION['cart']) AND is_array(@$_SESSION['cart'])){
   foreach($_SESSION['cart'] AS $itemquantity){
   $totalquantity = $totalquantity + $itemquantity['quantity'];
   }
}
else{
$totalquantity = 0;
}
echo $totalquantity;
4

2 回答 2

1

尝试类似:

  if(isset($_SESSION['cart']) && is_array($_SESSION['cart'])) {
        $totalquantity = 0;
        foreach($_SESSION['cart'] AS $productId => $itemQuanity) {
            $totalquantity = $totalquantity + $itemQuanity;
        }
  }
  else {
       $totalquantity = 0;
  }
  echo $totalquantity;

您可以将 foreach($_SESSION['cart'] AS $productId => $itemQuanity){ 替换为 foreach($_SESSION['cart'] AS $itemQuanity){ 因为您不需要密钥(这里的密钥是产品 ID) .

于 2012-09-26T18:35:40.593 回答
0

几个变化:AND是合乎逻辑的,你需要&&用于条件检查。另外,参数中is_array()不应该有 a @

   if(isset($_SESSION['cart']) && is_array($_SESSION['cart'])){ //change this line
     $totalquantity = 0;
     foreach($_SESSION['cart'] AS $itemquantity){
       $totalquantity +=  $itemquantity['quantity']; // and this line, just shorthand of ur line
      }
      }
     else{
     $totalquantity = 0;
     }
     echo $totalquantity;
于 2012-09-26T18:16:03.737 回答