php session 購物車類

來源:互聯網
上載者:User

 

<?phpclass Cart{public function Cart() {if(!isset($_SESSION['cart'])){$_SESSION['cart'] = array();}}/*添加商品param int $id 商品主鍵  string $name 商品名稱  float $price 商品價格  int $num 購物數量*/public  function addItem($id,$name,$price,$num,$img) {//如果該商品已存在則直接加其數量if (isset($_SESSION['cart'][$id])) {$this->incNum($id,$num);return;}$item = array();$item['id'] = $id;$item['name'] = $name;$item['price'] = $price;$item['num'] = $num;$item['img'] = $img;$_SESSION['cart'][$id] = $item;}/*修改購物車中的商品數量int $id 商品主鍵int $num 某商品修改後的數量,即直接把某商品的數量改為$num*/public function modNum($id,$num=1) {if (!isset($_SESSION['cart'][$id])) {return false;}$_SESSION['cart'][$id]['num'] = $num;}/*商品數量+1*/public function incNum($id,$num=1) {if (isset($_SESSION['cart'][$id])) {$_SESSION['cart'][$id]['num'] += $num;}}/*商品數量-1*/public function decNum($id,$num=1) {if (isset($_SESSION['cart'][$id])) {$_SESSION['cart'][$id]['num'] -= $num;}//如果減少後,數量為0,則把這個商品刪掉if ($_SESSION['cart'][$id]['num'] <1) {$this->delItem($id);}}/*刪除商品*/public function delItem($id) {unset($_SESSION['cart'][$id]);}/*擷取單個商品*/public function getItem($id) {return $_SESSION['cart'][$id];}/*查詢購物車中商品的種類*/public function getCnt() {return count($_SESSION['cart']);}/*查詢購物車中商品的個數*/public function getNum(){if ($this->getCnt() == 0) {//種數為0,個數也為0return 0;}$sum = 0;$data = $_SESSION['cart'];foreach ($data as $item) {$sum += $item['num'];}return $sum;}/*購物車中商品的總金額*/public function getPrice() {//數量為0,價錢為0if ($this->getCnt() == 0) {return 0;}$price = 0.00;foreach ($this->items as $item) {$price += $item['num'] * $item['price'];}return sprintf("%01.2f", $price);}/*清空購物車*/public function clear() {$_SESSION['cart'] = array();}}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.