php简单Session购物车功能function函数
2024-03-14 15:24:04
<?php // 启动会话 session_start(); // 初始化购物车 if (!isset($_SESSION['cart'])) { $_SESSION['cart'] = array(); } // 判断产品是否已经在购物车中 function isProductInCart($product_id) { if (isset($_SESSION['cart'][$product_id])) { return true; } return false; } // 添加商品到购物车 产品 ID (product_id)、产品名称 (product_name)、产品图片 (product_image) 和数量 (quantity) function addToCart($product_id, $product_name, $product_image, $quantity) { if (isProductInCart($product_id)) { // 产品已经在购物车中,更新数量 $_SESSION['cart'][$product_id]['quantity'] += $quantity; echo "产品已经添加到购物车中,并且数量已更新。"; } else { // 产品不在购物车中,添加新产品 $_SESSION['cart'][$product_id] = array( 'product_id' => $product_id, 'product_name' => $product_name, 'product_image' => $product_image, 'quantity' => $quantity ); echo "产品已成功添加到购物车中。"; } } // 更新购物车中商品的数量 function updateQuantity($product_id, $quantity) { if (isset($_SESSION['cart'][$product_id])) { $_SESSION['cart'][$product_id]['quantity'] = $quantity; } } // 清空购物车 function clearCart() { $_SESSION['cart'] = array(); } // 显示购物车中的商品列表 function displayCart() { if (!empty($_SESSION['cart'])) { foreach ($_SESSION['cart'] as $item) { echo "Product ID: " . $item['product_id'] . "<br>"; echo "Product Name: " . $item['product_name'] . "<br>"; echo "Product Image: " . $item['product_image'] . "<br>"; echo "Quantity: " . $item['quantity'] . "<br>"; echo "<br>"; } } else { echo "购物车为空"; } } // 测试添加商品到购物车 addToCart(1, "产品1", "image1.jpg", 2); addToCart(2, "产品2", "image2.jpg", 1); // 显示购物车中的商品列表 displayCart(); // 更新购物车中商品的数量 updateQuantity(1, 4); // 再次显示购物车中的商品列表 displayCart(); // 清空购物车 clearCart(); // 显示清空购物车后的商品列表 displayCart(); //单独判单 是否存在 if (isset($_SESSION['cart'][1])) { $product = $_SESSION['cart'][1]; // 现在 $product 变量中包含了产品 ID 为 1 的产品信息 $product_id = $product['product_id']; $product_name = $product['product_name']; $product_image = $product['product_image']; $quantity = $product['quantity']; // 然后您可以使用这些变量进行其他处理或显示 } else { // 产品 ID 为 1 的产品不存在于购物车中 } ?>
【责任编辑:超级管理员】
关键字:
好用的独立响应式css asp获取ip判断用户属于什么国家最新文章
2021-05-10 09:29
- pbootcms 上传的图片自动转换webp,达到最佳网站加载速度
- pbootcms模板里面写php判断的方法-判断session
- dede 电脑端和手机端首页同步生成方法,
- excel表格导入access中不换行解决办法-
- dede完美上下篇 英文版替换标签 dede:prenext 中英
- dede中英文网站栏目条调用方法
- dede双语站 面包导航{dede:field name='position'}
- PS: 无法完成请求,因为某种原因阻止文本引擎进行
- dede企业网站常见左侧固定大小类二级菜单调用代码
- 栏目页dede:channelartlist调用下级子类并dede:arcl
- dede:channelartlis 判断是否有子类栏目
- 更换织梦后台图集上传flash插件为layui上传模块
相关文章
2021-05-10 09:29