[英]Multidimensional array in php SESSION
我在使用 PHP 的$_SESSION
变量更新数组元素时遇到问题。 这是基本结构:
$product = array();
$product['id'] = $id;
$product['type'] = $type;
$product['quantity'] = $quantity;
然后通过使用array_push()
function 我将该产品插入 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']
变量中增加产品数量。 我怎样才能做到这一点?
不要盲目地将产品塞进会话中。 使用产品的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
这对你来说不是最好的答案......但希望可以帮助你们不是专家编码员,只是在这个论坛中学习编码^,^。你必须一直试图解决。 更多示例希望可以帮助更新价值数量:
<?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>
我之前遇到过同样的问题,并且接受的答案仅起作用,因为它直接修改了 session 变量,但是在foreach
循环中,您必须通过引用传递$product
变量(通过在其前面加上&
)才能保存更改,例如这个:
foreach($_SESSION['cart'] as &$product){
if($id == $product['id']){
$product['quantity'] += 1;
}
}
或者,如果您遵循公认的解决方案:
foreach($_SESSION['cart'] as $id => &$product){
if($searchId == $id){
$product['quantity'] += 1;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.