2013-02-25 72 views
0

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; 
} 
+1

'$ this-> cart [$ id] ['qty'] ++;'應該是'$ this-> cart [$ id] ['qty'] + = $ qty;' – 2013-02-25 17:41:08

+0

您能告訴我們'isInCart'方法? – 2013-02-25 17:41:31

+0

@JosephSilber爲什麼'+ =',而不是'++'?我學習PHP,我想知道什麼時候不用'++'。 – Kamil 2013-02-25 18:15:20

回答

3

當你將它添加到陣列中,你使用了數字鍵,而不是你的ID值:

$this->cart[] = array('id' => $id, 'qty' => $qty); 

將其更改爲:

$this->cart[$id] = array('id' => $id, 'qty' => $qty); 

將此更改合併到您的isInCart()方法中,您應該很好。

+0

感謝您的支持。我必須對我的foreach循環做一些其他更改,但事實上我是通過數字索引而不是id完全滑脫了我的想法! – useyourillusiontoo 2013-02-25 19:12:53

0
function addItem($id, $qty="1"){ 
... 
    $this->cart[$id]['qty']++; 
... 

將函數的第二個參數設置爲字符串。當你調用函數時,你又傳入一個字符串。

$basket->addItem('monkey','200'); 
$basket->addItem('dog', '10'); 
$basket->addItem('dog'); 

如果我有一些字符串$string = "123",我要儘量增加與$string++,我不是增加它的數值。從數字中取出的報價和預期

function addItem($id, $qty=1){ 
if (($this->isInCart($id)) == false){ 
    $this->cart[] = array('id' => $id, 'qty' => $qty); 
} else{ 
    $this->cart[$id]['qty']++; 
} 
} 

它應該工作,並調用函數一樣

$basket->addItem('monkey',200); 
$basket->addItem('dog', 10); 
$basket->addItem('dog'); 

如果你需要一個號碼,最好只使用一個號碼。如果$qty來自用戶輸入,我可以理解使用字符串,但如果是這種情況,則需要使用$qty = intval($qty)來獲取它的數字版本。