以下是一个简单的PHP购物车代码示例:
<?php
session_start();
// 添加商品到购物车
function addToCart($productId, $quantity) {
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
if (isset($_SESSION['cart'][$productId])) {
$_SESSION['cart'][$productId] += $quantity;
} else {
$_SESSION['cart'][$productId] = $quantity;
}
}
// 从购物车移除商品
function removeFromCart($productId) {
if (isset($_SESSION['cart'][$productId])) {
unset($_SESSION['cart'][$productId]);
}
}
// 更新购物车中商品的数量
function updateQuantity($productId, $quantity) {
if (isset($_SESSION['cart'][$productId])) {
$_SESSION['cart'][$productId] = $quantity;
}
}
// 获取购物车中的商品列表
function getCartItems() {
if (isset($_SESSION['cart'])) {
return $_SESSION['cart'];
} else {
return array();
}
}
// 清空购物车
function clearCart() {
unset($_SESSION['cart']);
}
?>
使用方法:
<?php
// 引入购物车代码
require_once('cart.php');
// 添加商品到购物车
addToCart(1, 2);
addToCart(2, 1);
// 更新购物车中商品的数量
updateQuantity(1, 3);
// 从购物车移除商品
removeFromCart(2);
// 获取购物车中的商品列表
$cartItems = getCartItems();
// 输出购物车中的商品列表
foreach ($cartItems as $productId => $quantity) {
echo "商品ID: " . $productId . " 数量: " . $quantity . "<br>";
}
// 清空购物车
clearCart();
?>
以上代码实现了一个简单的购物车功能,可以添加、移除、更新商品数量,并且可以获取购物车中的商品列表。购物车信息存储在session中,可以在不同页面间共享。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站