
本文实例讲述了PHP购物车类Cart.class.php定义与用法。分享给大家供大家参考,具体如下:
之前的开发人员使用了JS的技术开发了一套前台购物车(删除添加什么的都使用JS),但是浏览器兼容不好, 今天终于出问题了, 有个老外购物了产品, 由于使用了不知名的浏览器, chrome, opera…都有可能, 因此, 我多了一份工作, 重写购物车.
不打算再使用JS, 直接考虑php.
找到了一个购物车的类, 使用起来很方便.
相关学习推荐:PHP编程从入门到精通
Cart.class.php源码:
totalCount = 0;
$this->totalPrice = 0;
$this->cart = array();
}
// }}}
// {{{ add($item)
function add($item){
if(!is_array($item)||is_null($item)) return $this->cart;
if(!is_numeric(end($item))||(!is_numeric(prev($item)))) {
echo "价格和数量必须是数字";
return $this->cart;
}
reset($item); //这一句是必须的,因为上面的判断已经移动了数组的指标
$key = current($item);
if($key=="") return $this->cart;
if($this->_isExists($key)){ //商品是否已经存在?
$this->cart[$key]['count'] = end($item);
return $this->cart;
}
$this->cart[$key]['ID'] = $key;
$this->cart[$key]['name'] = next($item);
$this->cart[$key]['price'] = next($item);
$this->cart[$key]['count'] = next($item);
return $this->cart;
}
// }}}
// {{{ add($item)
function remove($key="",$count=""){
if($key=="") {
$this->cart = array();
return true;
}
if(!array_key_exists($key,$this->cart)) return false;
if($count==""){ //移去这一类商品
unset($this->cart[$key]);
}else{ //移去$count个商品
$this->cart[$key]['count'] -= $count;
if($this->cart[$key]['count']<=0) unset($this->cart[$key]);
}
return $this->cart;
}
// }}}
// {{{ modi($key,$value)
function modi($key,$value){
if(!$this->_isExists($key)) return $this->cart(); //不存在此商品,直接返回
if($value<=0){ // value 太小,全部删除
unset($this->cart[$key]);
return $this->cart;
}
$this->cart[$key]['count'] = $value;
return $this->cart;
}
function getCart(){
return $this->cart;
}
// }}}
// {{{ _isExists($key)
function _isExists($key)
{
if(isset($this->cart[$key])&&!empty($this->cart[$key])&&array_key_exists($key,$this->cart))
return true;
return false;
}
// }}}
// {{{ isEmpty()
function isEmpty(){
return !count($this->cart);
}
// }}}
// {{{ _stat()
function _stat(){
if($this->isEmpty()) return false;
foreach($this->cart as $item){
$this->totalCount = @end($item);
$this->totalPrices = @prev($item);
}
return true;
}
// }}}
// {{{ totalPrices()
function totalPrices(){
if($this->_stat())
return $this->totalPrices;
return 0;
}
// }}}
// {{{ isEmpty()
function totalCount(){
if($this->_stat())
return $this->totalCount;
return 0;
}
}//End Class Cart
?>使用该类的方法:
add($p);
}
if( ($_GET['action']=='remove')&&($_GET['key']!="") ) {
$items = $cart->remove($_GET['key']);
}
if( ($_SERVER['REQUEST_METHOD']=="POST")&&($_POST['action']=='modi') ){
$key = $_POST['key'];
$value = $_POST['value'];
for($i=0;$imodi($key[$i],$value[$i]);
}
}
$items = $cart->getCart();
//打印
echo "";
setlocale(LC_MONETARY, 'it_IT');
foreach($items as $item){
echo "";
echo "ID:".$item['ID'].""; echo " 产品:".$item['name']; echo " 单价:".$item['price']; echo " "; $sum = $item['count']*$item['price']; echo " 合计:".round($sum,2); echo " "; } echo ""; echo " "; echo "
";
?>
以上就是示例PHP购物车类Cart.class.php定义与用法的详细内容,更多请关注考高分网其它相关文章!


