我的多维数组有问题。
我在数组中有各种项目。
每个项目的名称和数量都显示在屏幕上,通过-和+按钮可以将每个项目的数量更改1。每个按钮都是一个返回到同一页面的表单。
下面的例子是当我点击-按钮时调用的函数。它应该从物品的数量中减去一。
它正确地从数量中减去一,并且item_id是正确的。但是,它没有更新正确的数组项。事实上,它似乎在创建一个新的数组项目,因为当按下减号按钮时,一个新项目出现在篮子中的其他项目下面。
我认为我在array_splice调用中没有引用正确的数组项。我认为我不应该在"array_splice($_SESSION["cart_array"]"之后说"$thisKey"。
但是,我不确定如何正确引用我想要的数组项。
请告知。
代码:
if (isset($_POST['itemMinus']) && $_POST['itemMinus'] != "") {
// Access the array and run code to remove that array index
$thisKey = $_POST['itemMinus'];
$thisKeyQuantity = $_POST['itemMinusQuantity'];
if (count($_SESSION["cart_array"]) <= 1) {
unset($_SESSION["cart_array"]);
} else {
array_splice($_SESSION["cart_array"], $thisKey, 1,
array(array("item_id" => $thisKey, "quantity" => $thisKeyQuantity - 1)));
}
}
/********/
解决方案:
非常感谢Jeroen Bollen对解决方案的贡献。我的代码现在是这样工作的:
if (isset($_POST['itemMinus']) && $_POST['itemMinus'] != "") {
// Access the array and run code to remove that array index
$thisKey = $_POST['itemMinus'];
$thisKeyQuantity = $_POST['itemMinusQuantity'];
if (count($_SESSION["cart_array"]) <= 1) {
unset($_SESSION["cart_array"]);
} else {
$i=0;
foreach($_SESSION['cart_array'] as $key => $value) {
if($value['item_id'] == $thisKey) {
array_splice($_SESSION["cart_array"], $i, 1, array(array("item_id" => $thisKey, "quantity" => $thisKeyQuantity - 1)));
break;
}
else{$i++;}//end if
}//end foreach
}//end else
}//end if POST
怎么样:
foreach($_SESSION['cart_array'] as $key => $value) {
if($value['item_id'] == $thisKey) {
$value['quantity']--;
break; // Stop the loop, we're done
}
}