[英]Multidimensional array in php SESSION
I am having problem with updating an array element with in $_SESSION
variable of PHP.我在使用 PHP 的
$_SESSION
变量更新数组元素时遇到问题。 This is the basic structure:这是基本结构:
$product = array();
$product['id'] = $id;
$product['type'] = $type;
$product['quantity'] = $quantity;
And then by using array_push()
function I insert that product in SESSION variable.然后通过使用
array_push()
function 我将该产品插入 SESSION 变量中。
array_push($_SESSION['cart'], $product);
Now this is the main part where im facing problem:现在这是我面临问题的主要部分:
foreach($_SESSION['cart'] as $product){
if($id == $product['id']){
$quantity = $product['quantity'];
$quantity += 1;
$product['quantity'] = $quantity;
}
}
I want to increment product quantity within $_SESSION['cart']
variable.我想在
$_SESSION['cart']
变量中增加产品数量。 How can I do that?我怎样才能做到这一点?
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:
使用产品的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
this not best answers for u...but hope can help u guys im not expert coders, and just learn coding in this forum ^,^ .You must always trying to solved. 这对你来说不是最好的答案......但希望可以帮助你们不是专家编码员,只是在这个论坛中学习编码^,^。你必须一直试图解决。 for more example hope can help to update value quantity:
更多示例希望可以帮助更新价值数量:
<?php
if(isset($_POST['test'])) {
$id =$_POST['id'];
$newitem = array(
'idproduk' => $id,
'nm_produk' => 'hoodie',
'img_produk' => 'images/produk/hodie.jpg',
'harga_produk' => '20',
'qty' => '2'
);
//if not empty
if(!empty($_SESSION['cart']))
{
//and if session cart same
if(isset($_SESSION['cart'][$id]) == $id) {
$_SESSION['cart'][$id]['qty']++;
} else {
//if not same put new storing
$_SESSION['cart'][$id] = $newitem;
}
} else {
$_SESSION['cart'] = array();
$_SESSION['cart'][$id] = $newitem;
}
}
?>
<form method="post">
<input type="text" name="id" value="1">
<input type="submit" name="test" value="test">
<input type="submit" name="unset" value="unset">
</form>
I faced the same issue before, and the accepted answer works only because it modifies the session variable directly, but in a foreach
loop, you must pass the $product
variable by reference (by prepending &
to it) to be able to save changes like this:我之前遇到过同样的问题,并且接受的答案仅起作用,因为它直接修改了 session 变量,但是在
foreach
循环中,您必须通过引用传递$product
变量(通过在其前面加上&
)才能保存更改,例如这个:
foreach($_SESSION['cart'] as &$product){
if($id == $product['id']){
$product['quantity'] += 1;
}
}
Or if you follow the accepted solution:或者,如果您遵循公认的解决方案:
foreach($_SESSION['cart'] as $id => &$product){
if($searchId == $id){
$product['quantity'] += 1;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.