我有下面的代碼,當按下刪除按鈕時,從數量中刪除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
你的問題是什麼? – Bono