2013-02-25 66 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)来获取它的数字版本。