【发布时间】:2018-03-07 12:53:02
【问题描述】:
我正在尝试为我的网站创建一个购物车,并希望能够将产品添加到购物篮中。
所以我在 cart.php 文件中创建了一个 ajax 帖子,如果它不存在,我会在其中启动一个会话,然后添加到它,或者如果它存在则只添加到会话中。
这在我没有像这样指定键时有效:
if(isset($_POST['product'])){
if (isset($_SESSION['cart'])) {
$_SESSION['cart'][] = $_POST['product'];
$_SESSION['cart'][] = $_POST['price'];
$_SESSION['cart'][] = $_POST['picture'];
$_SESSION['cart'][] = $_POST['quantity'];
} else {
//Session is not set, setting session now
$_SESSION['cart'] = array();
$_SESSION['cart'][] = $_POST['product'];
$_SESSION['cart'][] = $_POST['price'];
$_SESSION['cart'][] = $_POST['picture'];
$_SESSION['cart'][] = $_POST['quantity'];
}
}
这给了我一个这样的数组:
Array
(
[0] => Douche 1
[1] => 1200
[2] => cms/images/douche.jpg
[3] =>
[4] => Douche 1
[5] => 1200
[6] => cms/images/douche.jpg
[7] =>
[8] => Douche 1
[9] => 1200
[10] => cms/images/douche.jpg
[11] =>
[12] => Douche 1
[13] => 1200
[14] => cms/images/douche.jpg
[15] =>
)
但稍后我想循环结果,所以我需要键具有可用值而不仅仅是数字。所以我尝试了这个:
if(isset($_POST['product'])){
if (isset($_SESSION['cart'])) {
$_SESSION['cart']['product'] = $_POST['product'];
$_SESSION['cart']['price'] = $_POST['price'];
$_SESSION['cart']['picture'] = $_POST['picture'];
$_SESSION['cart']['quantity'] = $_POST['quantity'];
} else {
//Session is not set, setting session now
$_SESSION['cart'] = array();
$_SESSION['cart']['product'] = $_POST['product'];
$_SESSION['cart']['price'] = $_POST['price'];
$_SESSION['cart']['picture'] = $_POST['picture'];
$_SESSION['cart']['quantity'] = $_POST['quantity'];
}
}
这给了我以下结果:
Array
(
[product] => Douche 1
[price] => 1200
[picture] => cms/images/douche.jpg
[quantity] =>
)
它每次都会替换自己,所以我需要的是一个多维数组。我的问题:如何创建它?
这是我想要的结果:
Array
(
[0] => Array
(
[product] => Douche 1
[price] => 1200
[picture] => cms/images/douche.jpg
[quantity] =>
)
[1] => Array
(
[product] => Douche 1
[price] => 1200
[picture] => cms/images/douche.jpg
[quantity] => => 18
)
)
【问题讨论】:
-
删除这一行 $_SESSION['cart'] = array();