2014-02-08 88 views
1

我在更新PHP的$_SESSION变量的数组元素时遇到问题。这是基本结构:php中的多维数组SESSION

$product = array(); 
$product['id'] = $id; 
$product['type'] = $type; 
$product['quantity'] = $quantity; 

,然后使用array_push()功能我插入SESSION变量产品。

array_push($_SESSION['cart'], $product); 

现在,这是I M面临的问题主要部分:

foreach($_SESSION['cart'] as $product){ 

    if($id == $product['id']){ 
     $quantity = $product['quantity']; 
     $quantity += 1; 
     $product['quantity'] = $quantity;  
    } 

} 

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

回答

10

不要盲目地将产品放入会议中。使用该产品的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 
1

为U该不是最佳答案...但希望能帮助ü家伙 我不是专家程序员,和刚刚在这个论坛上学习编码^,^你一定要试着解决。 更多示例希望可以帮助更新数量值:

<?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>