0

I can't understand how to do this. This is my add to cart script:

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

This echos back things like this:

2:Array
3:Array
4:Array
5:Array

I think I am building $_SESSION['cart'] correctly, yes? I just don't understand how to echo them back properly.

EDIT: var_dump of $_SESSION after playing around with it for a bit:

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" } } }
2
  • 1
    what's var_dump() of $_SESSION ? Commented Aug 7, 2012 at 0:01
  • 1
    Use <pre> with print_r() for readability. Commented Aug 7, 2012 at 0:09

3 Answers 3

2

Your array looks like:

cart = Array(n){
         [0]=>  array(1){ ['SKU1'] => int(Quantity1)},
         [1]=>  array(1){ ['SKU2'] => int(Quantity2)},
...
}

so you should actually use it like this:

foreach($_SESSION['cart'] as $arr) {
    foreach($arr as $sku => $quantity) {
        echo $sku . ":" . $quantity . "<br/>";
    }    
}

Or, you can add the SKUs to the cart like this:

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

and then you'll be able to use your code "as is":

foreach($_SESSION['cart'] as $sku => $quantity) {
    echo $sku . ":" . $quantity "<br/>";
}
Sign up to request clarification or add additional context in comments.

Comments

0

Yes, you are doing it correctly. How you want to see result?

Comments

0

Do:

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

to use just the one foreach

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.