php购物车所有商品总和_PHP实现的购物车类实例

本文实例讲述了PHP实现的购物车类。分享给大家供大家参考。具体分析如下:

该购物车类是基于CodeIgniter的购物车类仿写实现的。

购物车基本功能如下:

1) 将物品加入购物车

2) 从购物车中删除物品

3) 更新购物车物品信息 【+1/-1】

4) 对购物车物品进行统计

1. 总项目

2. 总数量

3. 总金额

5) 对购物单项物品的数量及金额进行统计

6) 清空购物车

1. cart.php文件:

<?php

/**

*

* @author quanshuidingdang

*/

class Cart {

//物品id及名称规则,调试信息控制

private $product_id_rule = '\.a-z0-9-_'; //小写字母 | 数字 | ._-

private $product_name_rule = '\.\:a-z0-9-_';//小写字母 | 数字 | ._-:

private $debug = TRUE;

//购物车

private $_cart_contents = array();

/**

* 构造函数

*

* @param array

*/

public function __construct() {

//是否第一次使用?

if(isset($_SESSION['cart_contents'])) {

$this->_cart_contents = $_SESSION['cart_contents'];

} else {

$this->_cart_contents['cart_total'] = 0;

$this->_cart_contents['total_items'] = 0;

}

if($this->debug === TRUE) {

//$this->_log("cart_create_success");

}

}

/**

* 将物品加入购物车

*

* @access public

* @param array 一维或多维数组,必须包含键值名:

id -> 物品ID标识,

qty -> 数量(quantity),

price -> 单价(price),

name -> 物品姓名

* @return bool

*/

public function insert($items = array()) {

//输入物品参数异常

if( ! is_array($items) OR count($items) == 0) {

if($this->debug === TRUE) {

$this->_log("cart_no_items_insert");

}

return FALSE;

}

//物品参数处理

$save_cart = FALSE;

if(isset($items['id'])) {

if($this->_insert($items) === TRUE) {

$save_cart = TRUE;

}

} else {

foreach($items as $val) {

if(is_array($val) AND isset($val['id'])) {

if($this->_insert($val) == TRUE) {

$save_cart = TRUE;

}

}

}

}

//当插入成功后保存数据到session

if($save_cart) {

$this->_save_cart();

return TRUE;

}

return FALSE;

}

/**

* 更新购物车物品信息

*

* &

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值