将项添加到数组中,但如果它们存在于数组中,则增加该值

时间:2016-12-14 19:45:48

标签: php arrays

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

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}
 )

因此,itemid为1的值将增加到7.我还需要知道它的含义,在添加额外的2之前,只有6个瓜库存。我们不希望有人找到添加更多甜瓜的方法,那么我们现在就会留在库存领域!

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

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

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

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

继续我所做的事,包括最后的事实检查,感谢@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);
}
相关问题