0

我不明白该怎么做。这是我添加到购物车的脚本:

$_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" } } }
4

3 回答 3

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/>";
}
于 2012-08-07T00:09:59.210 回答
0

是的,你做得对。你想怎么看结果?

于 2012-08-07T00:02:45.480 回答
0

做:

$_SESSION['cart'][$_SESSION['sku']] = $_SESSION['quantity'];

只使用一个foreach

于 2012-08-07T00:13:35.450 回答