我将购物车数组保存在Cookie中,然后将其发送到购物车页面。每当我从另一个产品转到某个页面并点击添加到购物车时,它都不会将其添加到数组中,但似乎会覆盖它。
$uri = $_SERVER['REQUEST_URI'];
$pin = explode('/', $uri);
$id = $pin[3];
$product = $model->selectById($id, 'carpet');
$product = $product->fetch(PDO::FETCH_ASSOC);
$site_url = site_url();
if(!$product){
header("Location: $site_url./404");
}
if(isset($_POST['add'])){
$cart = [];
$cart[$product['id']] = [];
$cart[$product['id']]['product_name'] = $product['name'];
setcookie('cart', serialize($cart), time()+3600);
$cart = unserialize($_COOKIE['cart']);
dd($cart);
}
答案 0 :(得分:0)
您已经给出了答案:每次运行此脚本时,您都会覆盖购物车。变化:
$uri = $_SERVER['REQUEST_URI'];
$pin = explode('/', $uri);
$id = $pin[3];
$product = $model->selectById($id, 'carpet');
$product = $product->fetch(PDO::FETCH_ASSOC);
$site_url = site_url();
if(!$product){
header("Location: $site_url./404");
}
if(isset($_POST['add'])){
if ( isset($_COOKIE['cart']) )
$cart = unserialize($_COOKIE['cart']); // if cookie is set, get the contents of it
else
$cart = []; // else create an empty cart
// append new product and add to cart
$cart[$product['id']] = [];
$cart[$product['id']]['product_name'] = $product['name'];
setcookie('cart', serialize($cart), time()+3600);
$cart = unserialize($_COOKIE['cart']);
dd($cart);
}
答案 1 :(得分:0)
问题的第2部分:如何增加产品的订单数量:
...
// is this product alread in cart?
if ( isset($cart[$product['id']])
$prod = $cart[$product['id']]; // then pick it
else
{
// create a new product object
$prod = new stdClass();
// initialze with name and zer quantity
$prod->name = $product['name'];
$prod->quantity = 0;
}
// increment quantity
$prod->quantity ++;
// reassign to array
$cart[$product['id']] = $prod;
...