【问题标题】:Unable to increment PHP array variable in object无法在对象中增加 PHP 数组变量
【发布时间】: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


【解决方案1】:

当您将它添加到数组时,您使用的是数字键而不是您的 ID 值:

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

改成:

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

将此更改合并到您的 isInCart() 方法中,您应该会很好。

【讨论】:

  • 谢谢。我不得不对我的 foreach 循环进行一些其他更改,但事实上我是按数字而不是 id 进行索引的事实完全让我忘记了!
【解决方案2】:
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) 来获取它的数字版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-08
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    相关资源
    最近更新 更多