Norse
Norse

Reputation: 5757

PHP Add to Cart - how to create array?

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" } } }

Upvotes: 0

Views: 384

Answers (3)

Nir Alfasi
Nir Alfasi

Reputation: 53535

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

Upvotes: 2

Jaime
Jaime

Reputation: 1410

Do:

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

to use just the one foreach

Upvotes: 0

Zendy
Zendy

Reputation: 1684

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

Upvotes: 0

Related Questions