PHP populates multidimensional associative array - easiest way

I want to use $_SESSION

to store items in a cart. The elements are defined id

, each element has 3 sizes and the number of elements will be stored for each size. I would like to use a multidimensional associative array like this

$_SESSION['cart']['id'.$_GET['id']]['size'.$_POST['size']]['quantity'] += $_POST['quantity'];

      

but I think the problem I am getting ( Notice: Undefined index

) is that the arrays are not defined at first.

I would like it to be simple, so what would be the easiest way?

+3


source to share


2 answers


Your problem is that you are simply assuming the items are set to $_SESSION

. You have to assume they are not and start by adding them.

You would use 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
        ),
    );
}

      

Obviously you would change the above, perhaps just set the product ID as you need, then do the same type isset()

to add the selected dimensions. I'll just show you how to create an initial array of a struct.

+3


source


I would say that the best way to store this data is not in a multidimensional array, but in an object (not in $ _SESSION, but altogether different).

If you want to get closer to this object, I would use the following option:

$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 OOP approach to your program.

Disadvantages:

Storing an object in $ _SESSION can cause scalability problems .

+1


source







All Articles