Php 警告:正在添加值会话数组

Php 警告:正在添加值会话数组,php,arrays,session,cart,Php,Arrays,Session,Cart,我正在开发一个购物车系统,当我第一次尝试添加产品时,它总是给我一个警告,说: 注意:第9行的…/cart.php中的未定义索引:2 索引:2是id_乘积 $product=(isset($_SESSION['cart']) and $_SESSION['cart']!="") ? $_SESSION['cart'] : ""; if(isset($_POST['id_product'])){ $product= $_POST['id_product']; $qu

我正在开发一个购物车系统,当我第一次尝试添加产品时,它总是给我一个警告,说:

注意:第9行的…/cart.php中的未定义索引:2

索引:2是id_乘积

$product=(isset($_SESSION['cart']) and $_SESSION['cart']!="") ? $_SESSION['cart'] : "";

if(isset($_POST['id_product'])){
        $product= $_POST['id_product'];
        $quantity= $_POST['qty'];
        $_SESSION['cart'][$product]+=$quantity;
    }
它以同样的方式添加值,但在我刷新将显示在foreach表上的页面之后。我收到的值是正确的

我在登录另一个页面后定义默认值

$_SESSION['car'][0] = 0;

有什么建议吗

在语句
$\u SESSION['cart'][$product]+=$quantity您正在使用+=这就是导致问题的原因

当您第一次添加产品时,它将抛出错误,并且后续工作正常

要解决这个问题,你可以这样做

$quantity= $_POST['qty'];
if(!empty($_SESSION['cart'][$product])){
     $quantity = $quantity + $_SESSION['cart'][$product];
}
$_SESSION['cart'][$product] = $quantity;

您好,您需要将您的id_产品设置为有效变量

$product=(isset($_SESSION['cart']) and $_SESSION['cart']!="") ? $_SESSION['cart'] : "";

if(isset($_POST['id_product'])){
    $product= $_POST['id_product'];
    $quantity= $_POST['qty'];

    if(!isset($_SESSION['cart'][$product])) {
        $_SESSION['cart'][$product] = $quantity;
    } 
    else { 
        $_SESSION['cart'][$product]+=$quantity;
    }
}

谢谢你的支持,但对我没有帮助:/@AndréFerreira Your welcome.OMG!这不可能如此明显!非常感谢你的好意!