目前,我可以设置并保持所选产品的名称和价格到我的会话数组中。我需要扩展,以便我可以保持数量和身份。我不知道如何将更多的值存储到同一个数组中,如果可能的话,密钥是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);
}
答案 0 :(得分:1)
我想你可能想要使用multidimensional array。
// 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";
}
}