網(wǎng)站策劃模板百度推廣費用
?一個簡單的商城購物車功能。它使用了PHP的會話(Session)來存儲購物車數(shù)據(jù),通過調(diào)用不同的函數(shù)來實現(xiàn)添加商品、移除商品、更新商品數(shù)量以及清空購物車的功能
session_start();// 初始化購物車
if (!isset($_SESSION['cart'])) {$_SESSION['cart'] = array();
}// 添加商品到購物車
function addToCart($product_id, $quantity) {if (isset($_SESSION['cart'][$product_id])) {// 商品已存在購物車中,增加數(shù)量$_SESSION['cart'][$product_id] += $quantity;} else {// 商品不存在購物車中,添加到購物車$_SESSION['cart'][$product_id] = $quantity;}
}// 從購物車移除商品
function removeFromCart($product_id) {if (isset($_SESSION['cart'][$product_id])) {unset($_SESSION['cart'][$product_id]);}
}// 更新購物車中商品的數(shù)量
function updateQuantity($product_id, $quantity) {if (isset($_SESSION['cart'][$product_id])) {$_SESSION['cart'][$product_id] = $quantity;}
}// 清空購物車
function clearCart() {$_SESSION['cart'] = array();
}// 獲取購物車中的商品列表
function getCart() {return $_SESSION['cart'];
}