PHP SESSION中的多维数组 [英] Multidimensional array in php SESSION
本文介绍了PHP SESSION中的多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在用PHP的$_SESSION
变量更新数组元素时遇到问题.这是基本结构:
I am having problem with updating an array element with in $_SESSION
variable of PHP. This is the basic structure:
$product = array();
$product['id'] = $id;
$product['type'] = $type;
$product['quantity'] = $quantity;
然后使用array_push()
函数将产品插入SESSION变量中.
And then by using array_push()
function I insert that product in SESSION variable.
array_push($_SESSION['cart'], $product);
现在这是我面临问题的主要部分:
Now this is the main part where i m facing problem:
foreach($_SESSION['cart'] as $product){
if($id == $product['id']){
$quantity = $product['quantity'];
$quantity += 1;
$product['quantity'] = $quantity;
}
}
我想增加$_SESSION['cart']
变量中的产品数量.我该怎么办?
I want to increment product quantity within $_SESSION['cart']
variable. How can I do that?
推荐答案
不要盲目地将产品塞入您的会话中.使用产品的ID作为密钥,然后在购物车中查找/操作该物品很简单:
Don't blindly stuff the product into your session. Use the product's ID as the key, then it's trivial to find/manipulate that item in the cart:
$_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
这篇关于PHP SESSION中的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文