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