如何更改会话数组变量值

smi*_*121 2 php arrays session session-variables

我的会话中有一组“产品”,一个产品是一组名称、代码和数量,我想在按下“qty_up”按钮时更改数量:

我的 PHP 是这样的:

if ($_POST['qty_up']==''){
    foreach ($_SESSION["products"] as $key => $val)
    {
        if ($val["product_code"] == $_POST['code']) {
            $val["product_qty"] += 1;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这会更改 $val["product_qty"] 但不会更改会话中的实际值

这是我在会话中的“产品”数组:

array (size=1)
  'products' => 
    array (size=5)
      213453 => 
        array (size=5)
          'product_qty' => string '1' (length=1)
          'product_code' => string '213453' (length=6)
          'product_name' => string 'Kingfisher' (length=10)
          'product_price' => string '12.00' (length=5)
      48754 => 
        array (size=5)
          'product_qty' => string '1' (length=1)
          'product_code' => string '48754' (length=5)
          'product_name' => string 'Minute maid' (length=11)
          'product_price' => string '2.00' (length=4)
      '3545231ES0' => 
        array (size=5)
          'product_qty' => string '1' (length=1)
          'product_code' => string '3545231ES0' (length=10)
          'product_name' => string 'Jagurt' (length=6)
          'product_price' => string '1.00' (length=4)
Run Code Online (Sandbox Code Playgroud)

Obj*_*tor 5

这个 $val 需要什么?您可以直接更新会话值。

if ($_POST['qty_up']=='') {

   foreach ($_SESSION["products"] as $key => &$val) {

       if ($val["product_code"] == $_POST['code']) {
           //$val["product_qty"] += $val["product_qty"];
           $_SESSION["products"][$key]['product_qty'] +=  $val["product_qty"]; // Add this
       }

    }
}
Run Code Online (Sandbox Code Playgroud)