session_start();
/*
* 基于session的shopcart类
* caroltc
* 312493732@qq.com
* 2014/08/26
* */
class Shopcart{
/*
* template可拓展
* $shopcart = array(0=>array('goodsid'=>'','title'=>'','nums'=>'','price'=>''));
*/
/*添加商品到购物车*/
public static function addGoodsToShopcart($goodsdata){
$session_shopcart = Shopcart::getShopcart();
if(count($session_shopcart)>0){
/*如果购物车不为空*/
for($i=0;$i
if($session_shopcart[$i]['goodsid']==$goodsdata['id']){
$session_shopcart[$i]['nums']++;
$_SESSION['SJ_SHOPCART'] = serialize($session_shopcart);
return ;
}
}
$session_shopcart[count($session_shopcart)]=array('goodsid'=>$goodsdata['id'],'title'=>$goodsdata['title'],'nums'=>1,'price'=>$goodsdata['price']);
$_SESSION['SJ_SHOPCART'] = serialize($session_shopcart);
}else{
$session_shopcart[count($session_shopcart)]=array('goodsid'=>$goodsdata['id'],'title'=>$goodsdata['title'],'nums'=>1,'price'=>$goodsdata['price']);
$_SESSION['SJ_SHOPCART'] = serialize($session_shopcart);
}
}
/*解析购物车*/
public static function getShopcart(){
if(!empty($_SESSION['SJ_SHOPCART'])){
return unserialize($_SESSION['SJ_SHOPCART']);
}else{
$shopcart = array();
$_SESSION['SJ_SHOPCART'] = serialize($shopcart);
return $shopcart;
}
}
/*获取购物车商品总数量 */
public static function getShopcartNums(){
if(!$_SESSION['SJ_SHOPCART']){
return 0;
}else{
$session_shopcart = Shopcart::getShopcart();
$n=0;
for($i=0;$i
$n += $session_shopcart[$i]['nums'];
}
return $n;
}
}
/*获取购物车商品总价格 */
public static function getShopcartPrice(){
if(!$_SESSION['SJ_SHOPCART']){
return 0;
}else{
$session_shopcart=Shopcart::getShopcart();
$m=0;
for($i=0;$i
$m += $session_shopcart[$i]['nums']*$session_shopcart[$i]['price'];
}
return $m;
}
}
/*添加购物车商品数量*/
public static function setShopcartNumsAdd($goodsid){
$session_shopcart=Shopcart::getShopcart();
for($i=0;$i
if($session_shopcart[$i]['goodsid']==$goodsid){
$session_shopcart[$i]['nums']++;
$_SESSION['SJ_SHOPCART'] = serialize($session_shopcart);
return ;
}
}
}
/*减少购物车商品数量 */
public static function setShopcartNumsDel($goodsid){
$session_shopcart=Shopcart::getShopcart();
for($i=0;$i
if($session_shopcart[$i]['goodsid']==$goodsid){
$session_shopcart[$i]['nums']--;
if($session_shopcart[$i]['nums']<=0){
array_splice($session_shopcart,$i,1); //如果商品数量为0则直接删除
}
$_SESSION['SJ_SHOPCART'] = serialize($session_shopcart);
return ;
}
}
}
/*删除购物车一种商品*/
public static function delShopcartGoods($goodsid){
$session_shopcart=Shopcart::getShopcart();
for($i=0;$i
if($session_shopcart[$i]['goodsid']==$goodsid){
array_splice($session_shopcart,$i,1); //直接删除
$_SESSION['SJ_SHOPCART'] = serialize($session_shopcart);
return ;
}
}
}
/*清空购物车*/
public static function clearShopcart(){
$_SESSION['SJ_SHOPCART'] = null;
}
}
?>