我正在使用PHP,我想使用array_push()在SESSION中存储两个以上的产品。但问题是,array_push后,只有2个产品显示在购物车中。当我添加两个以上的产品时,它不会被添加到购物车中。
下面是我的代码:
$dataArray = array();
$cartArray = array(
$code=>array(
'id' => $id,
'name' =>$name,
'price' =>$price,
'quantity' =>1)
);
if(empty($_SESSION["shopping_cart"])) {
$_SESSION["shopping_cart"] = $cartArray;
}
else {
array_push($dataArray, $_SESSION["shopping_cart"], $cartArray);
$_SESSION['shopping_cart'] = $dataArray;
}
你可以像下面提到的那样直接给数组赋值。
$_SESSION['shopping_cart'][] = $dataArray;
它将创建一个二维数组"shopping_cart"每次添加$dataArray
它将存储在new key中,这样您就可以获得"shopping_cart"包含所有项的数组
php数组请在下面找到解决方案:
<php
$cartArray = [
[
'id' => $id,
'name' =>$name,
'price' =>$price,
'quantity' =>1
],
[
'id' => $id,
'name' =>$name,
'price' =>$price,
'quantity' =>1
]
];
if(isset($_SESSION["shopping_cart"])){
if(empty($_SESSION["shopping_cart"])) {
$_SESSION["shopping_cart"] = $cartArray;
}
else {
array_push($_SESSION["shopping_cart"], $cartArray);
}
}
?>