php SESSION中的多维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21652702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:19:37  来源:igfitidea点击:

Multidimensional array in php SESSION

phpsessionmultidimensional-array

提问by Sohail Malik

I am having problem with updating an array element with in $_SESSIONvariable of PHP. This is the basic structure:

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

$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()函数,我将该产品插入到 SESSION 变量中。

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

}

I want to increment product quantity within $_SESSION['cart']variable. How can I do that?

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

回答by Marc B

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

回答by Budi Liauw

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>