2014-04-06 56 views
0

我目前正在努力创建购物车。 它在我将数组存储到产品ID时起作用,但我也需要存储数量。购物车存货编号和数量

我有一个函数

public static function addToCart($data) { 
if(!isset($_SESSION['cart'])) { 
    $_SESSION['cart'] = array(); 
} 

else { 
    array_push($_SESSION['cart'], $data['id']); 
} 
} 

我也有一个函数来获取从车

public static function getCart() { 
if(count($_SESSION['cart'])>0) { 
    $ids = ""; 

    foreach($_SESSION['cart'] as $id) { 
    $ids = $ids . $id . ","; 
    } 

    $ids = rtrim($ids, ','); 

    $q = dibi::fetchAll("SELECT * FROM eshop_products WHERE idProduct IN ({$ids})"); 
    return $q; 
} else { 

} 
} 

项目然后我给你函数变量和使用的foreach。

$cart = Cart::getCart(); 

foreach($cart as $c) { 
echo $c['price']; 
} 

我到处,了解多维数组,但似乎没有为我工作

回答

2

我想我们可以放心地假设某个ID只需要存储一次,如果添加了另一个相同产品的数量,它可以与已经存在的数据合并。

因此,产品ID是足够的数组密钥,因为它是唯一的。
然后可以将数量存储为产品的值。

那么你车的存储将表现为

$_SESSION['cart'] = array(
    123 => 3 // Product 123 with quantity 3 
    254 => 1 // Product 254 with quantity 1 
); 

添加到购物车中,这会工作:

public static function addToCart($item, $quantity) { 
    if(!isset($_SESSION['cart'])) { 
     $_SESSION['cart'] = array(); 
    } 

    if(isset($_SESSION['cart'][$item])) { 
     $_SESSION['cart'][$item] += $quantity; 
    } else { 
     $_SESSION['cart'][$item] = $quantity; 
    } 
} 

以后要取回车的物品,你可以使用的foreach扩展形式:

foreach($_SESSION['cart'] as $id => $quantity) { 
    // ... 
} 
+0

谢谢。有用。 :) – George

2

您可以使用$_SESSION['cart']作为键 - >值数组,其中关键是productID和价值是quantity

$_SESSION['cart'] = array(5 => 1, 6 => 2); 

获取密钥数组使用array_keys。要在查询中使用ids,请使用implode