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