PHP会话多维数组未被分配任何值


PHP Session multidimensional array not getting assigned any values

按下按钮后,将3个值放入PHP中的多维数组中。在分配到相同的括号之前,我已经检查了值,它似乎有正确的值。然而,当我添加这样的值时:

if (isset($_POST['add_to_cart'])) {
    $count = count($_SESSION['shopping_cart']);
    echo "Count: $count<br />";
    $_SESSION['shopping_cart'][$count]['product_id'] = $_POST['product_id'];
    $_SESSION['shopping_cart'][$count]['tier'] = $_POST['tier'];
    $_SESSION['shopping_cart'][$count]['division'] = $_POST['division'];
}

输出显示数组$_SESSION['shopping_cart']为空并且没有值。

if (empty($_SESSION['shopping_cart'])) {
    echo "Your cart is empty.<br />";
}
else {
    //Display products in cart
    foreach($_SESSION['shopping_cart'] as $id => $product) {
        echo $product['tier'] . $product['division'] . "<br />";
    }
}

我得出的结论是,我以错误的方式分配了这些值。我做错了什么?谢谢你的帮助!

编辑:忘记添加数组一开始已经初始化!

if(!isset($_SESSION['shopping_cart'])) {
    $_SESSION['shopping_cart'] = array();
}

我忘记将session_start();添加到代码中。这就是Session数组不起作用的原因!感谢您的帮助@Will