Reputation: 607
I want to use $_SESSION
to store items in cart. The items are defined by id
, each item has 3 sizes and for each size there will be stored item's quantity. I would like to use multidimensional associative array like that
$_SESSION['cart']['id'.$_GET['id']]['size'.$_POST['size']]['quantity'] += $_POST['quantity'];
but I guess the problem which I am getting (Notice: Undefined index
) is because the arrays are not defined first.
I would like to keep it simple, so what would be the easiest way?
Upvotes: 3
Views: 135
Reputation: 2793
I'd argue the best manner to store this data isn't in a multidimensional array, but rather in an Object (and not in $_SESSION, but that's a whole different topic).
If you want to approach this with an object, I'd use a variation of the following:
$myItem = new stdClass;
$myItem->id = $_GET['id'];
$myItem->sizeOne = new stdClass;
$myItem->sizeOne->name = "sizeOne";
$myItem->sizeOne->quantity = 1;
// repeat for sizeTwo and sizeThree
$_SESSION['cart'][$myItem->id] = $myItem;
Benefits:
More of an OOP approach to your program.
Drawbacks:
Storing an Object in the $_SESSION may cause scalability issues.
Upvotes: 1
Reputation: 13128
Your issue is that you're just assuming the items are set in $_SESSION
. You need to assume they aren't and start by adding them in.
You'd harness isset()
.
if(!isset($_SESSION['cart']['id'.$_GET['id']])) {
$_SESSION['cart']['id'.$_GET['id']] = array(
'sizeONE' => array(
'quantity' => 0
),
'sizeTWO' => array(
'quantity' => 0
),
'sizeTHREE' => array(
'quantity' => 0
),
);
}
You'd obviously modify the above to probably only set the product id as you require then run through the same sort of isset()
to add the selected sizes. I'm just showing you how to create the initial structure array.
Upvotes: 3