【发布时间】:2018-01-20 23:12:40
【问题描述】:
我在会话中添加了一个数组(购物车)。现在要从购物车中删除一个项目,我尝试了这个逻辑。购物车工作正常,我可以在我的页面上看到购物车中的所有物品。删除逻辑没有给我任何错误,但也没有从会话中删除项目。
我做错了什么?
function addToCart(){
$this->layout = false;
$this->render(false);
$cart = array();
$tempcart = unserialize($this->Session->read("cart"));
if(isset($tempcart)){
$cart = $tempcart;
}
$productId = $this->request->data("id");
if(!$this->existsInCart($cart, $productId)){
$cart[] = array("productId" => $productId, "createdAt" => date());
$this->Session->write("cart", serialize($cart));
echo "added";
}
else
echo "duplicate";
}
function removeFromCart(){
$this->layout = false;
$this->render(false);
$cart = array();
$tempcart = unserialize($this->Session->read("cart"));
if(isset($tempcart)){
$cart = $tempcart;
}
$productId = $this->request->data("productId");
for($i=0;$i<count($cart);$i++){
$cartItem = $cart[$i]; // an array
if($cartItem["productId"]==$productId)
unset($cart[$i]);
}
$this->Session->write("cart", serialize($cart));
echo "removed";
}
【问题讨论】:
-
您是否在 $productId 中获得了一些值?还是$id??
-
@KuldeepChoudhary 智能捕捉!
-
实际上在表中它是 id,我点击一个产品并发送 productId 中的 id 值。正如我在谷歌浏览器开发者工具中检查的那样,它的工作原理