淡水刚刚写好的购物车。基于php5,很容易就可以改成php4兼容的。比较简单,很容易使用。就四个方法。
PHP代码
- <?php
- /**************************
- @Filename: cart.php
- @Version : 0.0.1
- @Author : 淡水河边
- @Update : 2008-5-27
- **************************/
- class cart{
- public $cartname;
- private $thecart;
- function __construct($catename){
- $_SESSION["$catename"] = array();
- $this->thecart = $_SESSION["$catename"];
- }
- public function update(array $arr){
- if(count($this->thecart)){
- $new_product = true;
- foreach ($this->thecart as $had)
- {
- if($had['id'] == $arr['id'])
- {
- $key = array_search($had,$this->thecart);
- $this->thecart[$key]['count'] += $arr['count'];
- $new_product = false;
- break;
- }
- }
- if($new_product){
- array_push($this->thecart,$arr);
- }
- }
- else
- {
- array_push($this->thecart,$arr);
- }
- }
- public function del($id){
- foreach ($this->thecart as $had)
- {
- if($had['id'] == $id)
- {
- $key = array_search($had,$this->thecart);
- unset($this->thecart[$key]);
- break;
- }
- }
- }
- public function discard(){
- unset($this->thecart);
- }
- public function show(){
- return $this->thecart;
- }
- }
- ?>
使用方法:
PHP代码
- //欲购商品
- $arr = array(
- 'id'=>'2',
- 'name'=>'兰花',
- 'price'=>'30',
- 'count'=>'50'
- );
- //实例一个对象
- $mycart = new cart('ppg');
- //放入购物车
- $mycart->update($arr);
- //删除车里不要的商品
- $mycart->del(3);
- //打印车里的商品
- print_r($mycart->show());
- //清空购物车
- $mycart->discard;


