返回列表 发帖

根据项目需要写的一个购物车程序(session的)

根据项目需要写的一个购物车程序(session的)

class GoodsCart{
public $mycart;   //购物车

//构造函数初始化购物车
function __construct($mycart){
   session_start();
   $this->mycart = $mycart;
   if(!isset($_SESSION[$mycart])){
    $_SESSION[$mycart] = array();
   }

}
//添加商品
public function AddOneGoods($date){
   $i = 0;
   session_start();
   if(empty($_SESSION[$this->mycart])){
    $i = 0;
   }else {
    $i = count($_SESSION[$this->mycart]);
   }
   foreach ($date as $key => $value){
    $_SESSION[$this->mycart][$i][$key] = $value;
   }
   $_SESSION[$this->mycart][$i]['id'] = $i;
}
//修改商品
public function EditCart($i,$date){
   if(array_key_exists($i,$_SESSION[$this->mycart]) == false){
    die('该商品不存在');
   }else {
    foreach ($date as $key => $value){
     $_SESSION[$this->mycart][$i][$key] = $value;
    }
   }
}
//删除一件商品
public function DelOne($id){
   if(count($_SESSION[$this->mycart]) ==1){
    unset($_SESSION[$this->mycart]);
   }else {
    unset($_SESSION[$this->mycart][$id]);
    $this->UpDate();
   }
   return true;
}
//清空购物车
public function DelCart(){
   unset($_SESSION[$this->mycart]);
}
//获得购物车数据
public function GetDate(){
   if(!empty($_SESSION[$this->mycart])){
    return $_SESSION[$this->mycart];
   }else {
    return array();
   }
}
public function UpDate(){
   $cart = $_SESSION[$this->mycart];
   $_SESSION[$this->mycart] = array();
   foreach ($cart as $v)
   array_push($_SESSION[$this->mycart],$v);
   for($i=0;$i<count($_SESSION[$this->mycart]);$i++){
    $_SESSION[$this->mycart][$i]['id'] = $i;
   }
}
public function GoodsCount($goods){
   $count = 0;
   for($i=0;$i<count($_SESSION[$this->mycart]);$i++){
    $count = $count + $_SESSION[$this->mycart][$i][$goods];
   }
   return $count;
}
}

返回列表