0

我的多维数组有问题。

我在数组中有各种项目。

每个项目的名称和数量显示在屏幕上,带有 - 和 + 按钮可将每个项目的数量更改为 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
4

1 回答 1

0

怎么样:

foreach($_SESSION['cart_array'] as $key => $value) {
    if($value['item_id'] == $thisKey) {
        $value['quantity']--;
        break; // Stop the loop, we're done
    }
}
于 2013-11-19T18:08:15.087 回答