【发布时间】:2013-10-23 17:06:11
【问题描述】:
当按下删除按钮时,我有以下代码从 qty 中删除 1,如果 qty=1,项目将从特定索引处的数组中删除。
例如,如果数组中的第一项的 ID 为“1B”且数量为“5”且名称为“item1”,则数组中的第二项的 ID 为“2B”且数量为“3”且名称为'item2' 并按下该项目的删除按钮,数量将更改为 2(根据需要),但 id 将更改为 1B,名称更改为 'item1'。如果$_SESSION["Cart"] 数组中有超过 2 个产品,也会发生同样的情况。
我不确定我哪里出错了,但这是我的代码:
$_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
【问题讨论】:
-
你有什么问题?
标签: php arrays session multidimensional-array