php加入购物车怎样实现_php购物车实现代码

php购物车实现代码这个代码比较全,需要的朋友可以参考下。

ShopCar.php

class Shopcar

{

//商品列表

public $productList=array();

/**

*

* @param unknown_type $product 传进来的商品

* @return true 购物车里面没有该商品

*/

public function checkProduct($product)

{

for($i=0;$iproductList);$i++ )

{

if($this->productList[$i]['name']==$product['name'])

return $i;

}

return -1;

}

//添加到购物车

public function add($product)

{

$i=$this->checkProduct($product);

if($i==-1)

array_push($this->productList,$product);

else

$this->productList[$i]['num']+=$product['num'];

}

//删除

public function delete($product)

{

$i=$this->checkProduct($product);

if($i!=-1)

array_splice($this->productList,$i,1);

}

//返回所有的商品的信息

public function show()

{

return $this->productList;

}

}

productList.html

Insert title here

function buy(i)

{

var num=$(':input[name=num]')[i].value;

var name=$('[name=name]')[i].innerHTML;

var price=$('[name=price]')[i].innerHTML;

alert(num+name+price);

$.ajax({

type:'post', //传送的方式,get/post

url:'index.php', //发送数据的地址

cache:'false',

data:'num='+num+"&name="+name+"&price="+price,

success:function(data)

{

alert(data);

}

})

}

商品编号商品名称价格数量购买
0商品11购买
1商品22购买
2商品31购买
3商品41购买
查看购物车

index.php

require 'Shopcar.class.php';

session_start();

$name=$_POST['name'];

$num=$_POST['num'];

$price=$_POST['price'];

$product=array('name'=>$name,'num'=>$num,'price'=>$price);

print_r($product);

if(isset($_SESSION['shopcar']))

$shopcar=unserialize($_SESSION['shopcar']);

else

$shopcar=new Shopcar();

$shopcar->add($product);

$_SESSION['shopcar']=serialize($shopcar);

show.php

商品编号商品名称价格数量

require 'Shopcar.class.php';

session_start();

$shopcar=unserialize($_SESSION['shopcar']);

print_r($shopcar);

$productList=$shopcar->productList;

foreach ($productList as $product){

?>

1<?php echo $product['name']?><?php echo $product['price']?>' />
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值