이 기사의 예에서는 PHP에서 CodeIgniter를 모방하는 장바구니 클래스를 구현하는 방법을 설명합니다. 참고할 수 있도록 모든 사람과 공유하세요. 세부 내용은 다음과 같습니다.
CodeIgniter의 장바구니 클래스를 따라해보세요
기본 장바구니 기능:
1) 장바구니에 상품 추가
2) 장바구니에서 상품 삭제
3) 장바구니 품목 정보 업데이트 [1/-1]
4) 장바구니 항목 통계
1. 전체 프로젝트
2. 총 수량
3. 총액
5) 쇼핑 품목 수량 및 금액 계산
6) 장바구니 비우기
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; } /** * 更新购物车物品信息 * * @access public * @param array * @return bool */ public function update($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['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; } } } } //当更新成功后保存数据到session if($save_cart) { $this->_save_cart(); return TRUE; } return FALSE; } /** * 获取购物车物品总金额 * * @return int */ public function total() { return $this->_cart_contents['cart_total']; } /** * 获取购物车物品种类 * * @return int */ public function total_items() { return $this->_cart_contents['total_items']; } /** * 获取购物车 * * @return array */ public function contents() { return $this->_cart_contents; } /** * 获取购物车物品options * * @param string * @return array */ public function options($rowid = '') { if($this->has_options($rowid)) { return $this->_cart_contents[$rowid]['options']; } else { return array(); } } /** * 清空购物车 * */ public function destroy() { unset($this->_cart_contents); $this->_cart_contents['cart_total'] = 0; $this->_cart_contents['total_items'] = 0; unset($_SESSION['cart_contents']); } /** * 判断购物车物品是否有options选项 * * @param string * @return bool */ private function has_options($rowid = '') { if( ! isset($this->_cart_contents[$rowid]['options']) OR count($this->_cart_contents[$rowid]['options']) === 0) { return FALSE; } return TRUE; } /** * 插入数据 * * @access private * @param array * @return bool */ private function _insert($items = array()) { //输入物品参数异常 if( ! is_array($items) OR count($items) == 0) { if($this->debug === TRUE) { $this->_log("cart_no_data_insert"); } return FALSE; } //如果物品参数无效(无id/qty/price/name) if( ! isset($items['id']) OR ! isset($items['qty']) OR ! isset($items['price']) OR ! isset($items['name'])) { if($this->debug === TRUE) { $this->_log("cart_items_data_invalid"); } 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) { if($this->debug === TRUE) { $this->_log("cart_items_data(qty)_invalid"); } return FALSE; } //物品ID正则判断 if( ! preg_match('/^['.$this->product_id_rule.']+$/i', $items['id'])) { if($this->debug === TRUE) { $this->_log("cart_items_data(id)_invalid"); } return FALSE; } //物品名称正则判断 if( ! preg_match('/^['.$this->product_name_rule.']+$/i', $items['name'])) { if($this->debug === TRUE) { $this->_log("cart_items_data(name)_invalid"); } 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'])) { if($this->debug === TRUE) { $this->_log("cart_items_data(price)_invalid"); } return FALSE; } //生成物品的唯一id if(isset($items['options']) AND count($items['options']) >0) { $rowid = md5($items['id'].implode('', $items['options'])); } else { $rowid = md5($items['id']); } //加入物品到购物车 unset($this->_cart_contents[$rowid]); $this->_cart_contents[$rowid]['rowid'] = $rowid; foreach($items as $key => $val) { $this->_cart_contents[$rowid][$key] = $val; } return TRUE; } /** * 更新购物车物品信息(私有) * * @access private * @param array * @return bool */ private function _update($items = array()) { //输入物品参数异常 if( ! isset($items['rowid']) OR ! isset($items['qty']) OR ! isset($this->_cart_contents[$items['rowid']])) { if($this->debug == TRUE) { $this->_log("cart_items_data_invalid"); } return FALSE; } //去除物品数量左零及非数字字符 $items['qty'] = preg_replace('/([^0-9])/i', '', $items['qty']); $items['qty'] = preg_replace('/^([0]+)/i', '', $items['qty']); //如果物品数量非数字,对购物车不做任何处理! if( ! is_numeric($items['qty'])) { if($this->debug === TRUE) { $this->_log("cart_items_data(qty)_invalid"); } return FALSE; } //如果购物车物品数量与需要更新的物品数量一致,则不需要更新 if($this->_cart_contents[$items['rowid']]['qty'] == $items['qty']) { if($this->debug === TRUE) { $this->_log("cart_items_data(qty)_equal"); } return FALSE; } //如果需要更新的物品数量等于0,表示不需要这件物品,从购物车种清除 //否则修改购物车物品数量等于输入的物品数量 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 */ private function _save_cart() { //首先清除购物车总物品种类及总金额 unset($this->_cart_contents['total_items']); unset($this->_cart_contents['cart_total']); //然后遍历数组统计物品种类及总金额 $total = 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']); //每种物品的总金额 $this->_cart_contents[$key]['subtotal'] = ($val['price'] * $val['qty']); } //设置购物车总物品种类及总金额 $this->_cart_contents['total_items'] = count($this->_cart_contents); $this->_cart_contents['cart_total'] = $total; //如果购物车的元素个数少于等于2,说明购物车为空 if(count($this->_cart_contents) <= 2) { unset($_SESSION['cart_contents']); return FALSE; } //保存购物车数据到session $_SESSION['cart_contents'] = $this->_cart_contents; return TRUE; } /** * 日志记录 * * @access private * @param string * @return bool */ private function _log($msg) { return @file_put_contents('cart_err.log', $msg, FILE_APPEND); } } /*End of file cart.php*/ /*Location /htdocs/cart.php*/
cart_demo.php 파일은 다음과 같습니다.
<?php session_start(); require_once('cart.php'); $items = array( 0 => array( 'id' => 'sp001', 'qty' => 20, 'price' => '10.50', 'name' => 'a002', 'options' => array( 'made' => 'china', 'company' => 'bgi' ) ), 1 => array( 'id' => 'sp002', 'qty' => 1, 'price' => '3.50', 'name' => 'b002' ) ); $arr = array( 'rowid' => '86dbb7cb58a667558b4bbb1f60330028', 'qty' => 21 ); $cart = new Cart(); $cart->insert($items); //var_dump($cart->contents()); $cart->update($arr); var_dump($cart->contents()); //$cart->destroy(); //var_dump($_SESSION['cart_contents']); /*end of php*/
이 기사가 모든 사람의 PHP 프로그래밍 설계에 도움이 되기를 바랍니다.

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

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

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

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