【问题标题】:deleting and changing values in multidimensional array php删除和更改多维数组php中的值
【发布时间】: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


【解决方案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

【讨论】:

    【解决方案2】:

    您的代码存在一些算法/逻辑缺陷。这段代码应该做你需要它做的事情。请尝试找出它实际上做了什么,以及您的方法中的缺陷在哪里。

    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;
    

    【讨论】:

      猜你喜欢
      • 2017-06-23
      • 2011-04-05
      • 1970-01-01
      • 1970-01-01
      • 2016-01-03
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      • 1970-01-01
      相关资源
      最近更新 更多