目前我能够设置并保存被选择到会话数组中的产品的名称和价格。我需要扩张以保持数量和id的平衡。我不知道如何有更多的值存储到相同的数组,这样,如果可能的关键是id?其次,我需要检查用户是否再次按下,然后只添加数量,其余信息保持不变?
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$price = isset($_GET['price']) ? $_GET['price'] : "";
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : "";
/*
* check if the 'cart' session array was created
* if it is NOT, create the 'cart' session array
*/
if(!isset($_SESSION['cart_items'])){
$_SESSION['cart_items'] = array();
}
// check if the item is in the array, if it is, do not add
if(array_key_exists($id, $_SESSION['cart_items'])){
// redirect to product list and tell the user it was added to cart
header('Location: products.php?action=exists&id' . $id . '&name=' . $name);
}
// else, add the item to the array
else{
$_SESSION['cart_items'][$name]=$price;
// redirect to product list and tell the user it was added to cart
header('Location: products.php?action=added&id' . $id . '&name=' . $name);
}
我想你可能需要使用多维数组。
// else, add the item to the array
else{
$_SESSION['cart_items'][$name]['price']=$price;
if (!empty($quantity)){
$_SESSION['cart_items'][$name]['quantity']=$quantity;
}
// redirect to product list and tell the user it was added to cart
header('Location: products.php?action=added&id' . $id . '&name=' . $name);
}
更新:为了访问数组的更深维度,可以使用嵌套循环。
foreach($_SESSION['cart_items'] as $name=>$value){
foreach($value as $key => $val){
echo "$name : $key = $val <br/>'n";
}
}