2013-10-23 31 views
0

我有下面的代碼,當按下刪除按鈕時,從數量中刪除1,如果qty = 1,該項目將從特定索引處的數組中刪除。刪除和更改多維數組中的值php

例如,如果數組中的第一項具有ID爲'1B'且數量爲'5'且名稱'item1'第二項具有ID爲'2B'且數量爲'3'且名稱'item2'並按下此項目的刪除按鈕,數量將變爲2(根據需要),但id將更改爲1B並將名稱改爲'item1'。如果$_SESSION["Cart"]陣列中有兩個以上產品,則會發生同樣的情況。
我不知道我要去哪裏錯了,但這是我的代碼:

代碼$_SESSION["Cart"]

$_SESSION["Cart"] = array(
      array(
       'name' => "namehere", 
       'id' => "idHere", 
       'qty' => 1, 
       'price' => "pricehere" 
      ) 
//more arrays here 
     ); 

代碼移除項目

$prodID = $_GET["removeProd"]; 
foreach ($_SESSION["Cart"] as $cartItem) { 
     //only continue if qty is more than one 
     //remove item if 0 qty 
     if ($cartItem["id"] == $prodID) { 
      if ($cartItem["qty"] > 1) { 
       $qty  = $cartItem["qty"] - 1; //decrease qty by one 
       $cart[] = array(
        'name' => $cartItem["name"], 
        'id' => $cartItem["id"], 
        'qty' => $qty, 
        'price' => $cartItem["price"] 
       ); 
      } //end if 
     } else { 
      $cart[] = array(
       'name' => $cartItem["name"], 
       'id' => $cartItem["id"], 
       'qty' => $cartItem["qty"], 
       'price' => $cartItem["price"] 
      ); 
     } //end else 
     $_SESSION["Cart"] = $cart; 
    } //end foreach 
+0

你的問題是什麼? – Bono

回答

1

的問題是,你在每個迭代分配$_SESSION['Cart'] = $cart,所以它只會包含了$_SESSION['Cart']陣列中的最後一項。如果將它移動到foreach的末尾,則代碼應該可以工作。

您可以通過引用$cartItem來簡化這一點。這樣你只修改匹配的數組元素:$prodID

foreach ($_SESSION['Cart'] as $key => &$cartItem) { 
    if ($cartItem['id'] == $prodID) { 
    if ($cartItem['qty'] > 1) { 
     $cartItem['qty'] -= 1; 
    } else { 
     unset($_SESSION['Cart'][$key]); 
    } 
    } 
} 
unset($cartItem); // break the binding 
+0

謝謝!這很好地工作 – Pindo

0

您的代碼有一些algorhithmic /邏輯缺陷。這段代碼應該做你需要它做的事情。請嘗試找出它的實際作用,以及您的方法中的缺陷在哪裏。

foreach ($_SESSION["Cart"] as $key=>$cartItem) { 
    //only continue if qty is more than one 
    //remove item if 0 qty 
    if ($cartItem["id"] == $prodID) { 
     if ($cartItem["qty"] > 1) { 
      $qty = $cartItem["qty"]--;// does the same thing as x = x - 1; //decrease qty by one 
      $cart[$key]['qty'] = $qty; 

     } //end if 
     else { 
      unset($cart[$key]); 
     } 
     break;// ends foreach loop (assuming there can be only one item of the same type in the cart) 
    } 
} //end foreach 

$_SESSION["Cart"] = $cart;