我无法理解如何做到这一点。这是我的购物车脚本:
$_SESSION['sku'] = $_POST['sku'];
$_SESSION['quantity'] = $_POST['quantity'];
$_SESSION['cart'][] = array($_SESSION['sku'] => $_SESSION['quantity']);
foreach($_SESSION['cart'] as $sku => $quantity) {
echo $sku . ":" . $quantity "<br/>";
}
这回事如下:
2:Array
3:Array
4:Array
5:Array
我认为我正在构建$_SESSION['cart']
,是吗?我只是不明白如何正确地回应它们。
编辑: 在玩了一会儿后,$ _SESSION的var_dump:
array(3) { ["sku"]=> &string(3) "503" ["quantity"]=> &string(1) "2" ["cart"]=> &array(17) { [0]=> array(1) { [506]=> string(1) "4" } [1]=> array(1) { [505]=> string(1) "2" } [2]=> array(1) { [505]=> string(1) "2" } [3]=> array(1) { [505]=> string(1) "2" } [4]=> array(1) { [505]=> string(1) "2" } [5]=> array(1) { [505]=> string(1) "2" } [6]=> array(1) { [505]=> string(1) "2" } [7]=> array(1) { [505]=> string(1) "2" } [8]=> array(1) { [505]=> string(1) "2" } [9]=> array(1) { [505]=> string(1) "2" } [10]=> array(1) { [506]=> string(0) "" } [11]=> array(1) { [505]=> string(1) "2" } [12]=> array(1) { [505]=> string(1) "2" } [13]=> array(1) { [503]=> string(1) "2" } [14]=> array(1) { [503]=> string(1) "2" } [15]=> array(1) { [503]=> string(1) "2" } [16]=> array(1) { [503]=> string(1) "2" } } }
答案 0 :(得分:2)
你的数组看起来像:
cart = Array(n){
[0]=> array(1){ ['SKU1'] => int(Quantity1)},
[1]=> array(1){ ['SKU2'] => int(Quantity2)},
...
}
所以你应该像这样使用它:
foreach($_SESSION['cart'] as $arr) {
foreach($arr as $sku => $quantity) {
echo $sku . ":" . $quantity . "<br/>";
}
}
或者,您可以将SKU添加到购物车中,如下所示:
$sku = $_SESSION['sku'];
$quantity = $_SESSION['quantity']);
$_SESSION['cart'][$sku] = $quantity;
然后您就可以“按原样”使用您的代码:
foreach($_SESSION['cart'] as $sku => $quantity) {
echo $sku . ":" . $quantity "<br/>";
}
答案 1 :(得分:0)
是的,你正确地做到了。你想怎么看结果?
答案 2 :(得分:0)
执行:
$_SESSION['cart'][$_SESSION['sku']] = $_SESSION['quantity'];
只使用一个foreach