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; } } } } ?>

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











C 언어에서 return의 사용법은 다음과 같습니다. 1. 반환 값 유형이 void인 함수의 경우 return 문을 사용하여 함수 실행을 조기에 종료할 수 있습니다. 2. 반환 값 유형이 void가 아닌 함수의 경우 return 문은 함수 실행을 종료하는 것입니다. 결과는 호출자에게 반환됩니다. 3. 함수 실행을 조기에 종료합니다. 함수 내부에서는 return 문을 사용하여 함수 실행을 조기에 종료할 수 있습니다. 함수가 값을 반환하지 않는 경우.

소스 코드: publicclassReturnFinallyDemo{publicstaticvoidmain(String[]args){System.out.println(case1());}publicstaticintcase1(){intx;try{x=1;returnx;}finally{x=3;}}}# 출력 위 코드의 출력은 간단히 결론을 내릴 수 있습니다. return은 finally 전에 실행됩니다. 바이트코드 수준에서 무슨 일이 일어나는지 살펴보겠습니다. 다음은 case1 메소드의 바이트코드 일부를 가로채서 소스 코드를 비교하여 각 명령어의 의미를 주석으로 표시합니다.

Vue3.2 설정 구문 설탕은 Vue3.0의 번거로운 설정을 해결하기 위해 단일 파일 구성 요소(SFC)에서 결합된 API를 사용하는 컴파일 타임 구문 설탕입니다. 사용 중 문제점 1. 사용 중에 import로 도입된 선언된 변수, 함수 및 컨텐츠를 반환할 필요가 없습니다. //소개된 컨텐츠 가져오기 import{getToday. }from'./utils'//변수 constmsg='안녕하세요!'//함수 func

Python에서 items() 메소드는 일반적으로 사전 객체에 사용되어 사전의 모든 키-값 쌍을 반환합니다. 이는 사전의 멤버 메소드이므로 해당 객체가 사전이 아닌 이상 어떤 객체에도 직접 사용할 수 없습니다.

JavaScript 함수는 외부 세계와 상호 작용하는 두 가지 인터페이스를 제공합니다. 매개 변수는 외부 정보를 수신하는 입구 역할을 하며, 반환 값은 작업 결과를 외부 세계에 피드백하는 출구 역할을 합니다. 다음 기사에서는 JavaScript 함수 반환 값을 이해하고 return 문의 사용법을 간략하게 분석하는 데 도움이 되기를 바랍니다.

Python의 반환값 반환 사용법은 함수가 return 문을 실행하면 실행이 즉시 중지되고 함수가 호출된 위치에 지정된 값이 반환된다는 것입니다. 자세한 사용법: 1. 단일 값을 반환합니다. 2. 여러 값을 반환합니다. 3. null 값을 반환합니다. 4. 함수 실행을 조기에 종료합니다.

JavaScript에서 return을 사용하려면 특정 코드 예제가 필요합니다. JavaScript에서 return 문은 함수에서 반환되는 값을 지정하는 데 사용됩니다. 함수 실행을 종료하는 데 사용할 수 있을 뿐만 아니라 함수가 호출된 위치에 값을 반환할 수도 있습니다. return 문에는 다음과 같은 일반적인 용도가 있습니다. 값 반환 return 문은 함수가 호출된 위치에 값을 반환하는 데 사용할 수 있습니다. 다음은 간단한 예입니다: functionadd(a,b){

1. this 키워드 1. this 유형: 호출되는 개체는 해당 개체의 참조 유형입니다. 2. 사용법 요약 1. this.data;//Access 속성 2. this.func();//Access 메서드 3.this ( );//이 클래스의 다른 생성자를 호출합니다. 3. 사용법 설명 1.this.data가 멤버 메서드에 사용됩니다. 이것이 추가되지 않으면 어떻게 되는지 살펴보겠습니다. classMyDate{publicintyear;publicintmonth;publicintday; 월,월){예
