我如何回应基于php会话的数组的总项目数量。

时间:2012-09-26 18:13:45

标签: php arrays session cart

我无法了解我的生活如何获得物品的总量。我一直在关注这个教程来建立一个网上商店。 http://jameshamilton.eu/content/simple-php-shopping-cart-tutorial

并且一切似乎都在教程中工作。但我需要将商品总数添加到购物车中。代码创建一个数组,其id和quantity-number作为存储在SESSION ['cart']中的数组。我一直在搞乱FOREACH代码,但我只得到购物车中其中一个项目的总数,og数组的总数。但我需要总数量的总和,而不是行的总和。

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

工作代码:

$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;

2 个答案:

答案 0 :(得分: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 =&gt; $ itemQuanity){with foreach($ _ SESSION ['cart'] AS $ itemQuanity){因为你不需要密钥(这里的密钥是产品ID)。

答案 1 :(得分:0)

一些更改:AND是合乎逻辑的,您需要使用&&进行条件检查。此外,is_array()参数中不应包含@

   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;