PHP SESSIONベースの超使いやすいショッピングカー類
3610 ワード
<?php
session_start();
/*
* session shopcart
* caroltc
* [email protected]
* 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<count($session_shopcart);$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<count($session_shopcart);$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<count($session_shopcart);$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<count($session_shopcart);$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<count($session_shopcart);$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<count($session_shopcart);$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;
}
}
?>