PHP SESSION中的多维数组

索伊尔·马利克(Sohail Malik)

我在用$_SESSIONPHP变量更新数组元素时遇到问题这是基本结构:

$product = array();
$product['id'] = $id;
$product['type'] = $type;
$product['quantity'] = $quantity;

然后通过使用array_push()函数,将该产品插入SESSION变量中。

array_push($_SESSION['cart'], $product); 

现在这是我面临问题的主要部分:

foreach($_SESSION['cart'] as $product){

    if($id == $product['id']){
        $quantity = $product['quantity'];
        $quantity += 1;
        $product['quantity'] = $quantity;       
    }

}

我想在$_SESSION['cart']变量内增加产品数量我怎样才能做到这一点?

马克·B

不要盲目地将产品塞入您的会话中。使用产品的ID作为密钥,然后在购物车中查找/操作该物品就很简单了:

$_SESSION['cart'] = array();
$_SESSION['cart'][$id] = array('type' => 'foo', 'quantity' => 42);

$_SESSION['cart'][$id]['quantity']++; // another of this item to the cart
unset($_SESSION['cart'][$id]); //remove the item from the cart

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章