搜索
首页后端开发php教程php实现购物车保存一天的类介绍

php实现购物车保存一天的类介绍

Aug 11, 2017 pm 01:32 PM
php介绍购物车

这篇文章主要为大家详细介绍了php实现保存周期为1天的购物车类,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了php购物车类的具体代码,供大家参考,具体内容如下

购物车类 Cookies 保存,保存周期为1天 注意:浏览器必须支持Cookie才能够使用

示例代码:


<?php
/**
 * 购物车类 Cookies 保存,保存周期为1天 注意:浏览器必须支持Cookie才能够使用
 */
class CartAPI {
  private $CartArray = array(); // 存放购物车的二维数组
  private $CartCount; // 统计购物车数量
  public $Expires = 86400; // Cookies过期时间,如果为0则不保存到本地 单位为秒
  /**
   * 构造函数 初始化操作 如果$Id不为空,则直接添加到购物车
   *
   */
  public function __construct($Id = "",$Name = "",$Price1 = "",$Price2 = "",$Price3 = "",$Count = "",$Image = "",$Expires = 86400) {
    if ($Id != "" && is_numeric($Id)) {
      $this->Expires = $Expires;
      $this->addCart($Id,$Name,$Price1,$Price2,$Price3,$Count,$Image);
    }
  }
  /**
   * 添加商品到购物车
   *
   * @param int $Id 商品的编号
   * @param string $Name 商品名称
   * @param decimal $Price1 商品价格
   * @param decimal $Price2 商品价格
   * @param decimal $Price3 商品价格
   * @param int $Count 商品数量
   * @param string $Image 商品图片
   * @return 如果商品存在,则在原来的数量上加1,并返回false
   */
  public function addCart($Id,$Name,$Price1,$Price2,$Price3,$Count,$Image) {
    $this->CartArray = $this->CartView(); // 把数据读取并写入数组
    if ($this->checkItem($Id)) { // 检测商品是否存在
      $this->ModifyCart($Id,$Count,0); // 商品数量加$Count
      return false;
    }
    $this->CartArray[0][$Id] = $Id;
    $this->CartArray[1][$Id] = $Name;
    $this->CartArray[2][$Id] = $Price1;
    $this->CartArray[3][$Id] = $Price2;
    $this->CartArray[4][$Id] = $Price3;
    $this->CartArray[5][$Id] = $Count;
    $this->CartArray[6][$Id] = $Image;
    $this->save();
  }
  /**
   * 修改购物车里的商品
   *
   * @param int $Id 商品编号
   * @param int $Count 商品数量
   * @param int $Flag 修改类型 0:加 1:减 2:修改 3:清空
   * @return 如果修改失败,则返回false
   */
  public function ModifyCart($Id, $Count, $Flag = "") {
    $tmpId = $Id;
    $this->CartArray = $this->CartView(); // 把数据读取并写入数组
    $tmpArray = &$this->CartArray; // 引用
    if (!is_array($tmpArray[0])) return false;
    if ($Id < 1) {
      return false;
    }
    foreach ($tmpArray[0] as $item) {
      if ($item === $tmpId) {
        switch ($Flag) {
          case 0: // 添加数量 一般$Count为1
            $tmpArray[5][$Id] += $Count;
            break;
          case 1: // 减少数量
            $tmpArray[5][$Id] -= $Count;
            break;
          case 2: // 修改数量
            if ($Count == 0) {
              unset($tmpArray[0][$Id]);
              unset($tmpArray[1][$Id]);
              unset($tmpArray[2][$Id]);
              unset($tmpArray[3][$Id]);
              unset($tmpArray[4][$Id]);
              unset($tmpArray[5][$Id]);
              unset($tmpArray[6][$Id]);
              break;
            } else {
              $tmpArray[5][$Id] = $Count;
              break;
            }
          case 3: // 清空商品
            unset($tmpArray[0][$Id]);
            unset($tmpArray[1][$Id]);
            unset($tmpArray[2][$Id]);
            unset($tmpArray[3][$Id]);
            unset($tmpArray[4][$Id]);
            unset($tmpArray[5][$Id]);
            unset($tmpArray[6][$Id]);
            break;
          default:
            break;
        }
      }
    }
    $this->save();
  }
  /**
   * 清空购物车
   *
   */
  public function RemoveAll() {
    $this->CartArray = array();
    $this->save();
  }
  /**
   * 查看购物车信息
   *
   * @return array 返回一个二维数组
   */
  public function CartView() {
    $cookie = stripslashes($_COOKIE[&#39;CartAPI&#39;]);
    if (!$cookie) return false;
    $tmpUnSerialize = unserialize($cookie);
    return $tmpUnSerialize;
  }
  /**
   * 检查购物车是否有商品
   *
   * @return bool 如果有商品,返回true,否则false
   */
  public function checkCart() {
    $tmpArray = $this->CartView();
    if (count($tmpArray[0]) < 1) {      
      return false;
    }
    return true;
  }
  /**
   * 商品统计
   *
   * @return array 返回一个一维数组 $arr[0]:产品1的总价格 $arr[1:产品2得总价格 $arr[2]:产品3的总价格 $arr[3]:产品的总数量
   */
  public function CountPrice() {
    $tmpArray = $this->CartArray = $this->CartView();
    $outArray = array(); //一维数组
    // 0 是产品1的总价格
    // 1 是产品2的总价格
    // 2 是产品3的总价格
    // 3 是产品的总数量
    $i = 0;
    if (is_array($tmpArray[0])) {
      foreach ($tmpArray[0] as $key=>$val) {
        $outArray[0] += $tmpArray[2][$key] * $tmpArray[5][$key];
        $outArray[1] += $tmpArray[3][$key] * $tmpArray[5][$key];
        $outArray[2] += $tmpArray[4][$key] * $tmpArray[5][$key];
        $outArray[3] += $tmpArray[5][$key];
        $i++;
      }
    }
    return $outArray;
  }
  /**
   * 统计商品数量
   *
   * @return int
   */
  public function CartCount() {
    $tmpArray = $this->CartView();
    $tmpCount = count($tmpArray[0]);
    $this->CartCount = $tmpCount;
    return $tmpCount;
  }
  /**
   * 保存商品 如果不使用构造方法,此方法必须使用
   *
   */
  public function save() {
    $tmpArray = $this->CartArray;
    $tmpSerialize = serialize($tmpArray);
    setcookie("CartAPI",$tmpSerialize,time()+$this->Expires);
  }
  /**
   * 检查购物车商品是否存在
   *
   * @param int $Id
   * @return bool 如果存在 true 否则false
   */
  private function checkItem($Id) {
    $tmpArray = $this->CartArray;
    if (!is_array($tmpArray[0])) return;
    foreach ($tmpArray[0] as $item) {
      if ($item === $Id) return true;
    }
    return false;
  }
}
?>

以上是php实现购物车保存一天的类介绍的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
unset()和session_destroy()有什么区别?unset()和session_destroy()有什么区别?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

在负载平衡的情况下,什么是粘性会话(会话亲和力)?在负载平衡的情况下,什么是粘性会话(会话亲和力)?May 04, 2025 am 12:16 AM

stickysessensureuserRequestSarerOutedTothesMeServerForsessionDataConsisterency.1)sessionIdentificeAssificationAssigeaSsignAssignSignSuserServerServerSustersusiseCookiesorUrlModifications.2)一致的ententRoutingDirectSsssssubsequeSssubsequeSubsequestrequestSameSameserver.3)loadBellankingDisteributesNebutesneNewuserEreNevuseRe.3)

PHP中有哪些不同的会话保存处理程序?PHP中有哪些不同的会话保存处理程序?May 04, 2025 am 12:14 AM

phpoffersvarioussessionsionsavehandlers:1)文件:默认,简单的ButMayBottLeneckonHigh-trafficsites.2)Memcached:高性能,Idealforsforspeed-Criticalapplications.3)REDIS:redis:similartomemememememcached,withddeddeddedpassistence.4)withddeddedpassistence.4)databases:gelifforcontrati forforcontrati,有用

PHP中的会话是什么?为什么使用它们?PHP中的会话是什么?为什么使用它们?May 04, 2025 am 12:12 AM

PHP中的session是用于在服务器端保存用户数据以在多个请求之间保持状态的机制。具体来说,1)session通过session_start()函数启动,并通过$_SESSION超级全局数组存储和读取数据;2)session数据默认存储在服务器的临时文件中,但可通过数据库或内存存储优化;3)使用session可以实现用户登录状态跟踪和购物车管理等功能;4)需要注意session的安全传输和性能优化,以确保应用的安全性和效率。

说明PHP会话的生命周期。说明PHP会话的生命周期。May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

绝对会话超时有什么区别?绝对会话超时有什么区别?May 03, 2025 am 12:21 AM

绝对会话超时从会话创建时开始计时,闲置会话超时则从用户无操作时开始计时。绝对会话超时适用于需要严格控制会话生命周期的场景,如金融应用;闲置会话超时适合希望用户长时间保持会话活跃的应用,如社交媒体。

如果会话在服务器上不起作用,您将采取什么步骤?如果会话在服务器上不起作用,您将采取什么步骤?May 03, 2025 am 12:19 AM

服务器会话失效可以通过以下步骤解决:1.检查服务器配置,确保会话设置正确。2.验证客户端cookies,确认浏览器支持并正确发送。3.检查会话存储服务,如Redis,确保其正常运行。4.审查应用代码,确保会话逻辑正确。通过这些步骤,可以有效诊断和修复会话问题,提升用户体验。

session_start()函数的意义是什么?session_start()函数的意义是什么?May 03, 2025 am 12:18 AM

session_start()iscucialinphpformanagingusersessions.1)ItInitiateSanewsessionifnoneexists,2)resumesanexistingsessions,and3)setsasesessionCookieforContinuityActinuityAccontinuityAcconActInityAcconActInityAcconAccRequests,EnablingApplicationsApplicationsLikeUseAppericationLikeUseAthenticationalticationaltication and PersersonalizedContentent。

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脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。