PHP不断向购物车添加一行新的产品(如果已经存在的话)


PHP keeps adding a new line of a product to cart if already exists

我只是想知道是否有人能告诉我这个代码不工作的原因?

if($cart_count == 0)
{
    $_SESSION['cart'][] = $tmp_product;
} else if($cart_count > 0) {
    // if the array has anything in it:
    for($i=0; $i<$cart_count; $i++)
    { 
        // loop through the array rows:
        // if the id of the product already is in there then add to it:
        if($_SESSION['cart'][$i]['id'] === $tmp_product['id'])
        {
            // adds to the already there qty: preincrement actually I think
            $_SESSION['cart'][$i]['qty'] += $tmp_product['qty'];                
        } else {
            // otherwise add to it regardless of the conditional kind of...
            $_SESSION['cart'][] = $tmp_product;
        }
    }
}

我的意思是,我认为我的逻辑是正确的,当我把第一个产品添加到购物车中,然后再添加更多产品时,有什么理由吗。

尽管当我转到第一个添加的行之外的另一个独特的产品时,为什么每次我去添加时,它都会在会话中添加额外的行?这真的很奇怪,我似乎无法理解,当然这是我没有看到的。

为了更好地理解这一点,我输出了一个它不应该做什么的例子:

Array
(
    [cart] => Array
    (
        [0] => Array
        (
            [id] => 1
            [name] => Product Test 1
            [price] => 12.55
            [qty] => 1
        )
        [1] => Array
        (
            [id] => 2
            [name] => Product 2
            [price] => 52.22
            [qty] => 9
        )
        [2] => Array
        (
            [id] => 2
            [name] => Product 2
            [price] => 52.22
            [qty] => 6
        )
    )
)

嗯,奇怪。我不知道我是否走上了正轨,但我对你的代码做了一些更改。

  • 我删除了if($cart_count > 0)。如果从购物车中删除项目的逻辑是正确的,那么$cart_count永远不会低于零。而且,如果一个案例将$cart_count与0进行比较,那么其他案例只剩下一个案例,这允许跳过零以上的比较
  • 在for语句中:每次找不到项目(因为已经在卡中)时,都会插入一个新项目。您可以通过向代码中添加echo 'adding product';来查看调用的频率
  • 我已经将其更改为插入产品,如果已经存在,则突破for循环。并添加了标志$product_already_there

也许你可以玩一玩,看看它是否成功。


if($cart_count === 0) {                 // no items in the cart
    $_SESSION['cart'][] = $tmp_product; // add first item
} else {
    // there are already items in the cart array
    $product_already_there = false;
    // if product is already in the cart, increase product quantity
    for($i = 0; $i < $cart_count; $i++)
    {     
        if($_SESSION['cart'][$i]['id'] === $tmp_product['id']) {
            $_SESSION['cart'][$i]['qty'] = $_SESSION['cart'][$i]['qty'] + $tmp_product['qty'];
            $product_already_there = true;
            break;
        }
    }
    // else add a new product to the cart
    if($product_already_there === false) {
         $_SESSION['cart'][] = $tmp_product;
    }
}