【问题标题】:Adding items to an array, but if they exist in array, increase that value将项目添加到数组中,但如果它们存在于数组中,则增加该值
【发布时间】:2025-12-06 17:30:01
【问题描述】:

今天我正在为用户网站脚本编写购物车。当他们将商品添加到购物车时,它会存储在名为 cartitems$_SESSION 变量中。我将数组存储在 $_SESSION['cartitems'] 的数组中,其中包含项目的 itemid 以及他们尝试添加到购物车的项目数量。使用我在下面列出的代码简单地添加项目效果很好,但我需要它们增加数组中项目的值,假设他们尝试添加更多相同的项目,而不是简单地将新数组添加到会话中。举个例子:

-> User 1 visits the website.
    - Add 5 melons to cart.
    - Add 3 lemons to cart.
    - Add 2 more melons to cart.

我的数组会打印如下内容:

 array(
        array{0 => 1, 1 => 5},
        array{0 => 2, 1 => 3},
        array{0 => 1, 1 => 2}
 )

.. 而添加它们的目标是如下所示:

 array(
        array{0 => 1, 1 => 7},
        array{0 => 2, 1 => 3}
 )

所以 itemid 的值 1 将增加到 7。我还需要知道它的位置,在添加额外的 2 之前,以防库存中只有 6 个瓜。我们不希望有人找到一种方法来添加更多的甜瓜,然后我们现在会留在库存领域!

我已经传递了库存字段数量,以及天气它有无限的库存支持,或者对一个项目的购买限制,所以我有我需要限制东西的所有信息(我在添加项目时已经这样做了),只需要一种方法来更改数组,如果它已经在那里增加数量就可以了。这是我用来添加项目的代码:

if(isset($_POST['quantity'])) {
    // Cast quantity to an int for protection
    $quantity = (int) $_POST['quantity'];
    if(!empty($quantity) && $quantity > 0) {
        $errors = 0;
        // It doesn't support unlimited stock so we check stock level
        if($unlimstock == "0") {
            if($quantity > $stock) {
                $quantity = $stock;
            }
            if($buylimit > 0) {
                if($quantity > $buylimit) {
                    $errors = "1";
                }
            }
        }
        if($errors == 0) {
            $_SESSION['cartitems'][] = array($itemid, $quantity);
            header("Location: cart.php");
            die();
        }
    }
}

检查它是否在数组中的最佳方法是什么,如果它增加值,如果不是,我可以像现在一样添加它,如果是,那么值是多少所以我知道它可以增加。谢谢大家!

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    为了简化代码,您的 $_SESSION['cartitems'] 应将数据存储为:

    $_SESSION['cartitems'] = [
        'product_id1' => 'quantity1',
        'product_id2' => 'quantity2',
    ];
    

    那么更新一个数量就是:

    if (isset($_SESSION['cartitems'][$product_id])) {
        $_SESSION['cartitems'][$product_id] += $quantity;
    } else {
        $_SESSION['cartitems'][$product_id] = $quantity;
    }
    

    如果无法更改$_SESSION['cartitems'] 结构,则必须对其进行迭代:

    $found = false;
    foreach ($_SESSION['cartitems'] as $key => $item) {
        // I suppose that 0-indexed element stores id
        if ($item[0] == $product_id) {
            // I suppose that 1-indexed element stores quantity
            $_SESSION['cartitems'][$key][1] += $quantity;
            $found = true;
    
            // break as certain element found
            break;
        }
    }
    if (!$found) {
        $_SESSION['cartitems'][] = array($product_id, $quantity);
    }
    

    【讨论】:

    • 如果遇到困难,我为您当前的$_SESSION 添加了代码。所以你可以比较哪个更简单)
    • 第二个选项效果更好,因为它更容易使用当前结构实现,而且我不一定知道会话中的所有项目,因此需要更多的写作才能使第一个选项起作用,但第二个选项效果很好。现在只需要添加我的支票,看看它是否超过了库存限制。
    【解决方案2】:

    感谢@u_mulder,这就是我所做的,包括最后的事实核查:

    // Set that we dont't see it by default
    $found = false;
    foreach($_SESSION['cartitems'] as $key => $item) {
        if($item[0] == $itemid) {
            // If it has unlimited stock, who cares, otherwise fact check it
            if($unlimstock == "1") {
                $_SESSION['cartitems'][$key][1] += $quantity;
                $found = true;
                break;
            } else {
                // If it's less than or equal to stock, we can try and add it
                if(($_SESSION['cartitems'][$key][1] + $quantity) <= $stock) {
                    // If it has a buy limit, we set max to buy limit and check it
                    if($buylimit > 0) {
                        if(($_SESSION['cartitems'][$key][1] + $quantity) <= $buylimit) {
                            $_SESSION['cartitems'][$key][1] += $quantity;
                        }
                    } else {
                        $_SESSION['cartitems'][$key][1] += $quantity;
                    }
                }
                // Woot, we found it, so we can update it
                $found = true;
                break;
            }
        }
    }
    // If it wasn't found, we can add it as a new item. This has been fact checked already
    if(!$found) {
        $_SESSION['cartitems'][] = array($itemid, $quantity);
    }
    

    【讨论】: