Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP fill up multidimensional associative array - easiest way

Tags:

arrays

php

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?

like image 608
koubin Avatar asked Sep 18 '26 00:09

koubin


2 Answers

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.

like image 148
Darren Avatar answered Sep 19 '26 14:09

Darren


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.

like image 28
Adam Link Avatar answered Sep 19 '26 14:09

Adam Link



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!