搜索
首页后端开发php教程 PHP购物车种,移植于CodeIgniter

PHP购物车类,移植于CodeIgniter

<?php /**
 * 购物车程序 Modified by CodeIgniter
 *
 */
class cart {

	// 对产品ID和产品名称进行正则验证属性
	var $product_id_rules	= '\.a-z0-9_-';
	var $product_name_rules	= '\.\:\-_ a-z0-9'; // 考虑到汉字,该功能暂不使用

	// 私有变量
	var $_cart_contents	= array();


	/**
	 * 构造方法
	 *
	 */
	public function __construct()
	{
		if ($this->session('cart_contents') !== FALSE)
		{
			$this->_cart_contents = $this->session('cart_contents');
		}
		else
		{
			// 初始化数据
			$this->_cart_contents['cart_total'] = 0;
			$this->_cart_contents['total_items'] = 0;
		}
	}

	// --------------------------------

	/**
	 * 添加到购物车
	 *
	 * @access	public
	 * @param	array
	 * @return	bool
	 */
	function insert($items = array())
	{
		// 检测数据是否正确
		if ( ! is_array($items) OR count($items) == 0)
		{
			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;
					}
				}
			}
		}
		// 更新数据
		if ($save_cart == TRUE)
		{
			$this->_save_cart();
			return TRUE;
		}

		return FALSE;
	}

	// --------------------------------

	/**
	 * 处理插入购物车数据
	 *
	 * @access	private
	 * @param	array
	 * @return	bool
	 */
	function _insert($items = array())
	{
		// 检查购物车
		if ( ! is_array($items) OR count($items) == 0)
		{
			return FALSE;
		}

		// --------------------------------

		/* 前四个数组索引 (id, qty, price 和name) 是 必需的。
		   如果缺少其中的任何一个,数据将不会被保存到购物车中。
		   第5个索引 (options) 是可选的。当你的商品包含一些相关的选项信息时,你就可以使用它。
		   请使用一个数组来保存选项信息。注意:$data['price'] 的值必须大于0 
		   如:$data = array(
               'id'      => 'sku_123ABC',
               'qty'     => 1,
               'price'   => 39.95,
               'name'    => 'T-Shirt',
               'options' => array('Size' => 'L', 'Color' => 'Red')
            );
		*/

		if ( ! isset($items['id']) OR ! isset($items['qty']) OR ! isset($items['price']) OR ! isset($items['name']))
		{
			return FALSE;
		}

		// --------------------------------

		// 数量验证,不是数字替换为空
		$items['qty'] = trim(preg_replace('/([^0-9])/i', '', $items['qty']));
		// 数量验证
		$items['qty'] = trim(preg_replace('/(^[0]+)/i', '', $items['qty']));

		// 数量必须是数字或不为0
		if ( ! is_numeric($items['qty']) OR $items['qty'] == 0)
		{
			return FALSE;
		}

		// --------------------------------

		// 产品ID验证
		if ( ! preg_match("/^[".$this->product_id_rules."]+$/i", $items['id']))
		{
			return FALSE;
		}

		// --------------------------------

		// 验证产品名称,考虑到汉字,暂不使用
		/*
		if ( ! preg_match("/^[".$this->product_name_rules."]+$/i", $items['name']))
		{
			return FALSE;
		}
		*/

		// --------------------------------

		// 价格验证
		$items['price'] = trim(preg_replace('/([^0-9\.])/i', '', $items['price']));
		$items['price'] = trim(preg_replace('/(^[0]+)/i', '', $items['price']));

		// 验证价格是否是数值
		if ( ! is_numeric($items['price']))
		{
			return FALSE;
		}

		// --------------------------------

		// 属性验证,如果属性存在,属性值+产品ID进行加密保存在$rowid中
		if (isset($items['options']) AND count($items['options']) > 0)
		{
			$rowid = md5($items['id'].implode('', $items['options']));
		}
		else
		{
			// 没有属性时直接对产品ID加密
			$rowid = md5($items['id']);
		}
		
		// 检测购物车中是否有该产品,如果有,在原来的基础上加上本次新增的商品数量
		$_contents = $this->_cart_contents;
		$_tmp_contents = array();
		foreach ($_contents as $val)
		{
			if (is_array($val) AND isset($val['rowid']) AND isset($val['qty']) AND $val['rowid']==$rowid)
			{
				$_tmp_contents[$val['rowid']]['qty'] = $val['qty'];
			} else {
				$_tmp_contents[$val['rowid']]['qty'] = 0;
			}
		}
		// --------------------------------

		// 清除原来的数据
		unset($this->_cart_contents[$rowid]);

		// 重新赋值
		$this->_cart_contents[$rowid]['rowid'] = $rowid;

		// 添加新项目
		foreach ($items as $key => $val)
		{
			if ($key=='qty' && isset($_tmp_contents[$rowid][$key])) {
				$this->_cart_contents[$rowid][$key] = $val+$_tmp_contents[$rowid][$key];
			} else {
				$this->_cart_contents[$rowid][$key] = $val;
			}
		}

		return TRUE;
	}

	// --------------------------------

	/**
	 * 更新购物车
	 * 
	 * @access	public
	 * @param	array
	 * @param	string
	 * @return	bool
	 */
	function update($items = array())
	{
		// 验证
		if ( ! is_array($items) OR count($items) == 0)
		{
			return FALSE;
		}

		$save_cart = FALSE;
		if (isset($items['rowid']) AND isset($items['qty']))
		{
			if ($this->_update($items) == TRUE)
			{
				$save_cart = TRUE;
			}
		}
		else
		{
			foreach ($items as $val)
			{
				if (is_array($val) AND isset($val['rowid']) AND isset($val['qty']))
				{
					if ($this->_update($val) == TRUE)
					{
						$save_cart = TRUE;
					}
				}
			}
		}

		if ($save_cart == TRUE)
		{
			$this->_save_cart();
			return TRUE;
		}

		return FALSE;
	}

	// --------------------------------

	/**
	 * 处理更新购物车
	 *
	 * @access	private
	 * @param	array
	 * @return	bool
	 */
	function _update($items = array())
	{
		if ( ! isset($items['qty']) OR ! isset($items['rowid']) OR ! isset($this->_cart_contents[$items['rowid']]))
		{
			return FALSE;
		}

		// 检测数量
		$items['qty'] = preg_replace('/([^0-9])/i', '', $items['qty']);

		if ( ! is_numeric($items['qty']))
		{
			return FALSE;
		}

		if ($this->_cart_contents[$items['rowid']]['qty'] == $items['qty'])
		{
			return FALSE;
		}

		if ($items['qty'] == 0)
		{
			unset($this->_cart_contents[$items['rowid']]);
		}
		else
		{
			$this->_cart_contents[$items['rowid']]['qty'] = $items['qty'];
		}

		return TRUE;
	}

	// --------------------------------

	/**
	 * 保存购物车到Session里
	 *
	 * @access	private
	 * @return	bool
	 */
	function _save_cart()
	{
		unset($this->_cart_contents['total_items']);
		unset($this->_cart_contents['cart_total']);

		$total = 0;
		$items = 0;
		foreach ($this->_cart_contents as $key => $val)
		{
			if ( ! is_array($val) OR ! isset($val['price']) OR ! isset($val['qty']))
			{
				continue;
			}

			$total += ($val['price'] * $val['qty']);
			$items += $val['qty'];

			$this->_cart_contents[$key]['subtotal'] = ($this->_cart_contents[$key]['price'] * $this->_cart_contents[$key]['qty']);
		}

		$this->_cart_contents['total_items'] = $items;
		$this->_cart_contents['cart_total'] = $total;

		if (count($this->_cart_contents) session('cart_contents', array());

			return FALSE;
		}
		$this->session('cart_contents',$this->_cart_contents);

		return TRUE;
	}

	// --------------------------------

	/**
	 * 购物车中的总计金额
	 *
	 * @access	public
	 * @return	integer
	 */
	function total()
	{
		return $this->_cart_contents['cart_total'];
	}

	// --------------------------------

	/**
	 * 购物车中总共的项目数量
	 *
	 *
	 * @access	public
	 * @return	integer
	 */
	function total_items()
	{
		return $this->_cart_contents['total_items'];
	}

	// --------------------------------

	/**
	 * 购物车中所有信息的数组
	 *
	 * 返回一个包含了购物车中所有信息的数组
	 *
	 * @access	public
	 * @return	array
	 */
	function contents()
	{
		$cart = $this->_cart_contents;

		unset($cart['total_items']);
		unset($cart['cart_total']);

		return $cart;
	}

	// --------------------------------

	/**
	 * 购物车中是否有特定的列包含选项信息
	 *
	 * 如果购物车中特定的列包含选项信息,本函数会返回 TRUE(布尔值),本函数被设计为与 contents() 一起在循环中使用
	 *
	 * @access	public
	 * @return	array
	 */
	function has_options($rowid = '')
	{
		if ( ! isset($this->_cart_contents[$rowid]['options']) OR count($this->_cart_contents[$rowid]['options']) === 0)
		{
			return FALSE;
		}

		return TRUE;
	}

	// --------------------------------

	/**
	 * 以数组的形式返回特定商品的选项信息
	 *
	 * 本函数被设计为与 contents() 一起在循环中使用
	 *
	 * @access	public
	 * @return	array
	 */
	function product_options($rowid = '')
	{
		if ( ! isset($this->_cart_contents[$rowid]['options']))
		{
			return array();
		}

		return $this->_cart_contents[$rowid]['options'];
	}

	// --------------------------------

	/**
	 * 格式化数值
	 *
	 * 返回格式化后带小数点的值(小数点后有2位),一般价格使用
	 *
	 * @access	public
	 * @return	integer
	 */
	function format_number($n = '')
	{
		if ($n == '')
		{
			return '';
		}

		$n = trim(preg_replace('/([^0-9\.])/i', '', $n));

		return number_format($n, 2, '.', ',');
	}

	// --------------------------------

	/**
	 * 销毁购物车
	 *
	 * 这个函数一般是在处理完用户订单后调用
	 *
	 * @access	public
	 * @return	null
	 */
	function destroy()
	{
		unset($this->_cart_contents);

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

		$this->session('cart_contents', array());
	}
	
	// --------------------------------

	/**
	 * 保存Session
	 *
	 * 须有session_start();
	 *
	 * @access	private
	 * @return	bool
	 */
	function session($name = 'cart_contents',$value = NULL) {
		if ($name=='') $name = 'cart_contents';
		if ($value == NULL) {
			return @$_SESSION[$name];
		} else {
			if (!empty($value) && is_array($value)) {
				$_SESSION[$name] = $value;
				return TRUE;
			} else {
				return FALSE;
			}
		}
	}
}
?>
声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
C语言return的用法详解C语言return的用法详解Oct 07, 2023 am 10:58 AM

C语言return的用法有:1、对于返回值类型为void的函数,可以使用return语句来提前结束函数的执行;2、对于返回值类型不为void的函数,return语句的作用是将函数的执行结果返回给调用者;3、提前结束函数的执行,在函数内部,我们可以使用return语句来提前结束函数的执行,即使函数并没有返回值。

Java中return和finally语句的执行顺序是怎样的?Java中return和finally语句的执行顺序是怎样的?Apr 25, 2023 pm 07:55 PM

源码:publicclassReturnFinallyDemo{publicstaticvoidmain(String[]args){System.out.println(case1());}publicstaticintcase1(){intx;try{x=1;returnx;}finally{x=3;}}}#输出上述代码的输出可以简单地得出结论:return在finally之前执行,我们来看下字节码层面上发生了什么事情。下面截取case1方法的部分字节码,并且对照源码,将每个指令的含义注释在

Vue3怎么使用setup语法糖拒绝写returnVue3怎么使用setup语法糖拒绝写returnMay 12, 2023 pm 06:34 PM

Vue3.2setup语法糖是在单文件组件(SFC)中使用组合式API的编译时语法糖解决Vue3.0中setup需要繁琐将声明的变量、函数以及import引入的内容通过return向外暴露,才能在使用的问题1.在使用中无需return声明的变量、函数以及import引入的内容,即可在使用语法糖//import引入的内容import{getToday}from&#39;./utils&#39;//变量constmsg=&#39;Hello!&#39;//函数func

python中items怎么用python中items怎么用Nov 28, 2023 am 11:29 AM

在Python中,items()方法通常用于字典(dictionary)对象,用于返回字典的所有键值对(key-value pairs)。这是一个字典的成员方法,因此你不能直接对任何对象使用它,除非那个对象是一个字典。

详解JavaScript函数返回值和return语句详解JavaScript函数返回值和return语句Aug 04, 2022 am 09:46 AM

JavaScript 函数提供两个接口实现与外界的交互,其中参数作为入口,接收外界信息;返回值作为出口,把运算结果反馈给外界。下面本篇文章带大家了解一下JavaScript函数返回值,浅析下return语句的用法,希望对大家有所帮助!

Python返回值return怎么用Python返回值return怎么用Oct 07, 2023 am 11:10 AM

Python返回值return用法是当函数执行到return语句时,将立即停止执行,并将指定的值返回给调用函数的地方。详细用法:1、返回单个值;2、返回多个值;3、返回空值;4、提前结束函数的执行。

使用JavaScript中return关键字使用JavaScript中return关键字Feb 18, 2024 pm 12:45 PM

JavaScript中return的用法,需要具体代码示例在JavaScript中,return语句用于指定从函数中返回的值。它不仅可以用于结束函数的执行,还可以将一个值返回给调用函数的地方。return语句有以下几个常见的用法:返回一个值return语句可以用来返回一个值给调用函数的地方。下面是一个简单的示例:functionadd(a,b){

Java中this方法怎么使用Java中this方法怎么使用Apr 18, 2023 pm 01:58 PM

一、this关键字1.this的类型:哪个对象调用就是哪个对象的引用类型二、用法总结1.this.data;//访问属性2.this.func();//访问方法3.this();//调用本类中其他构造方法三、解释用法1.this.data这种是在成员方法中使用让我们来看看不加this会出现什么样的状况classMyDate{publicintyear;publicintmonth;publicintday;publicvoidsetDate(intyear,intmonth,intday){ye

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前By尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版