Multidimensional array in php SESSION

前端 未结 2 800
北恋
北恋 2020-12-08 18:12

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

$product = array();
$product[         


        
相关标签:
2条回答
  • 2020-12-08 18:31

    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
    
    0 讨论(0)
  • 2020-12-08 18:35

    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>
    
    0 讨论(0)
提交回复
热议问题