PHP数组变量我加入到我的购物车是这样的:无法递增对象
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;' – 2013-02-25 17:41:08
您能告诉我们'isInCart'方法? – 2013-02-25 17:41:31
@JosephSilber为什么'+ =',而不是'++'?我学习PHP,我想知道什么时候不用'++'。 – Kamil 2013-02-25 18:15:20