2014-02-08 92 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>