首頁 後端開發 php教程 PHP购物车种,移植于CodeIgniter

PHP购物车种,移植于CodeIgniter

Jun 13, 2016 pm 01:13 PM
items return this

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

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

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語法糖拒絕寫return Vue3怎麼使用setup語法糖拒絕寫return May 12, 2023 pm 06:34 PM

Vue3.2setup語法糖是在單文件組件(SFC)中使用組合式API的編譯時語法糖解決Vue3.0中setup需要繁瑣將聲明的變量、函數以及import引入的內容通過return向外暴露,才能在使用的問題1.在使用中無需return宣告的變數、函數以及import引入的內容,即可在使用語法糖//import引入的內容import{getToday}from'./utils'//變數constmsg='Hello !'//函數func

聊聊Vue2為什麼能透過this存取各種選項中屬性 聊聊Vue2為什麼能透過this存取各種選項中屬性 Dec 08, 2022 pm 08:22 PM

這篇文章帶大家解讀vue原始碼,來介紹一下Vue2中為什麼可以使用 this 存取各種選項中的屬性,希望對大家有幫助!

一篇搞懂this指向,追趕70%的前端人 一篇搞懂this指向,追趕70%的前端人 Sep 06, 2022 pm 05:03 PM

同事因為this指向的問題卡住的bug,vue2的this指向問題,使用了箭頭函數,導致拿不到對應的props。當我跟他介紹的時候他竟然不知道,隨後也刻意的看了一下前端交流群,至今最起碼還有70%以上的前端程式設計師搞不明白,今天給大家分享一下this指向,如果啥都沒學會,請給我一個大嘴巴子。

使用JavaScript中return關鍵字 使用JavaScript中return關鍵字 Feb 18, 2024 pm 12:45 PM

JavaScript中return的用法,需要具體程式碼範例在JavaScript中,return語句用來指定從函數傳回的值。它不僅可以用於結束函數的執行,還可以將一個值傳回給呼叫函數的地方。 return語句有以下幾個常見的用法:傳回一個值return語句可以用來傳回一個值給呼叫函數的地方。下面是一個簡單的範例:functionadd(a,b){

詳解JavaScript函數傳回值和return語句 詳解JavaScript函數傳回值和return語句 Aug 04, 2022 am 09:46 AM

JavaScript 函數提供兩個介面實現與外界的交互,其中參數作為入口,接收外界資訊;返回值作為出口,並將運算結果回饋給外界。以下這篇文章帶大家了解JavaScript函數回傳值,淺析下return語句的用法,希望對大家有幫助!

JavaScript如何使用return語句 JavaScript如何使用return語句 Feb 26, 2024 am 09:21 AM

JavaScript中return的使用方法,需要具體程式碼範例在JavaScript中,return是一個非常重要的關鍵字,它通常用於函數中傳回值或結束函數的執行。 return語句用來將值傳回給函數的呼叫者,並終止函數的執行。 return語句可以在函數的任何位置使用,並且可以傳回任何JavaScript資料類型,包括數字、字串、布林值、

See all articles