【发布时间】:2013-02-25 17:39:51
【问题描述】:
我正在像这样添加到我的购物车:
function addItem($id, $qty="1"){
if (($this->isInCart($id)) == false){
$this->cart[] = array( 'id' => $id, 'qty' => $qty);
} else{
$this->cart[$id]['qty']++;
}
}
如果一个项目已经在我的购物车中,我只需告诉方法将当前 $id 加一,但这似乎不适用于这些调用:
$basket->addItem('monkey','200');
$basket->addItem('dog', '10');
$basket->addItem('dog');
在第二次添加狗项时,以下函数仅报告我的篮子中只有 10 条狗:
function numberOfProduct($id){
unset($number);
foreach($this->cart as $n ){
if ($n['id'] == $id){
$number = $number + $n['qty'];
}
}
return $number;
}
我确定问题在于我在 addToBasket 方法中递增数组,但是当我在过程编码中使用完全相同的方法时,它可以正常工作。
我真的有点卡住了。
编辑:按要求在购物车方法中
function isInCart($id){
$inCart=false;
$itemsInCart=count($this->cart);
if ($itemsInCart > 0){
foreach($this->cart as $cart){
if ($cart['id']==$id){
return $inCart=true;
break;
}
}
}
return $inCart;
}
【问题讨论】:
-
$this->cart[$id]['qty']++;应该是$this->cart[$id]['qty'] += $qty; -
你能告诉我们
isInCart方法吗? -
@JosephSilber 为什么是
+=,而不是++?我正在学习 PHP,我想知道什么时候不使用++。 -
@Kamil - 因为使用
++意味着当您将已经存在的商品添加到购物车时,您忽略了输入参数$qty。如果有人在他们的购物车中添加了 10 只猴子,那么单步执行您的代码,然后再添加 10 只猴子。会发生什么? -
@nickb 我知道。我认为在对象中的关联数组上使用
++在 PHP 或类似的东西中可能不起作用。
标签: php arrays shopping-cart