PHP 添加超过 2 个项目时会话数组不工作

PHP Session Array not working when adding more than 2 items

我想将产品添加到我的数组中,但每次添加产品时,它都会替换数组中的旧产品。

当我添加 2 个东西时,它工作正常:

Array ( [0] => 2 [1] => 8 )

但是当我尝试添加第三个或更多项时,它会替换数组中的第二个项:

Array ( [0] => 2 [1] => 10 )

这是我的代码:

  session_start();

  if(isset($_POST['inCart']))
  {
       $id = $_POST['id'];

       if(!empty($_SESSION['cart']))
       {     
          $session = $_SESSION['cart'];
          $session[] = $id;

          print_r($session);
       }

       else
       {
          $_SESSION['cart'] = array($id); 
       }
  }

我看到你忘记用新数据设置 SESSION

if(!empty($_SESSION['cart']))
       {     
          $session = $_SESSION['cart'];
          $session[] = $id;

          $_SESSION['cart'] = $session;

          print_r($session);
       }