淡水的购物车

淡水刚刚写好的购物车。基于php5,很容易就可以改成php4兼容的。比较简单,很容易使用。就四个方法。

PHP代码
  1. <?php   
  2. /**************************  
  3. @Filename: cart.php  
  4. @Version : 0.0.1  
  5. @Author  : 淡水河边  
  6. @Update  : 2008-5-27  
  7. **************************/  
  8.     class cart{   
  9.         public $cartname;   
  10.         private $thecart;   
  11.            
  12.         function __construct($catename){   
  13.             $_SESSION["$catename"] = array();   
  14.             $this->thecart = $_SESSION["$catename"];   
  15.         }   
  16.            
  17.         public function update(array $arr){   
  18.             if(count($this->thecart)){   
  19.                 $new_product = true;   
  20.                 foreach ($this->thecart as $had)   
  21.                 {   
  22.                     if($had['id'] == $arr['id'])   
  23.                     {   
  24.                         $key = array_search($had,$this->thecart);   
  25.                         $this->thecart[$key]['count'] += $arr['count'];   
  26.                         $new_product = false;   
  27.                         break;   
  28.                     }   
  29.                 }   
  30.                    
  31.                 if($new_product){   
  32.                     array_push($this->thecart,$arr);   
  33.                 }   
  34.             }   
  35.             else  
  36.             {   
  37.                 array_push($this->thecart,$arr);   
  38.             }   
  39.         }   
  40.            
  41.         public function del($id){   
  42.             foreach ($this->thecart as $had)   
  43.             {   
  44.                 if($had['id'] == $id)   
  45.                 {   
  46.                     $key = array_search($had,$this->thecart);   
  47.                     unset($this->thecart[$key]);   
  48.                     break;   
  49.                 }   
  50.             }   
  51.         }   
  52.            
  53.         public function discard(){   
  54.             unset($this->thecart);   
  55.         }   
  56.            
  57.         public function show(){   
  58.             return $this->thecart;   
  59.         }   
  60.     }   
  61. ?>  

使用方法:

PHP代码
  1. //欲购商品   
  2. $arr = array(   
  3.             'id'=>'2',   
  4.             'name'=>'兰花',   
  5.             'price'=>'30',   
  6.             'count'=>'50'  
  7.             );   
  8. //实例一个对象   
  9. $mycart = new cart('ppg');   
  10. //放入购物车   
  11. $mycart->update($arr);   
  12. //删除车里不要的商品   
  13. $mycart->del(3);   
  14. //打印车里的商品   
  15. print_r($mycart->show());   
  16. //清空购物车   
  17. $mycart->discard;  

Tags: 购物车

« 上一篇 | 下一篇 »

Trackbacks

点击获得Trackback地址,Encode: UTF-8 点击获得Trackback地址,Encode: GB2312 or GBK 点击获得Trackback地址,Encode: BIG5

发表评论

评论内容 (必填):