AddToCart-System: array_push pushes on the "wrong level"?

129 Views Asked by At

I'm trying to make an "add to cart" function with this code:

if (empty($_SESSION['cart'])) {
    $_SESSION['cart'] = array(
        "id" => $_GET['id'],
        "size" => $_POST['size'],
        "count" => $_POST['count']
    );
} else {
    array_push($_SESSION['cart'], array(
        "id" => $_GET['id'],
        "size" => $_POST['size'],
        "count" => $_POST['count']
    ));
}

This is the output of print_r($_SESSION):

Array
(
    [cart] => Array
        (
            [id] => 1
            [size] => XS
            [count] => 1
            [0] => Array
                (
                    [id] => 2
                    [size] => XS
                    [count] => 1
                )
        )
)

You can see in the array what's wrong about my method pushing it. I want the new pushed content on the same "level" as the first entry above, if you know what I mean?

2

There are 2 best solutions below

3
On BEST ANSWER

I'm not sure what do you mean by "the new pushed content on the same "level" as the first entry above", following scenario is impossible:

$c = array(
           'id' => 1,
           'size' => 'X5',
           'count' => 1,

            // YOU CAN'T HAVE DUPLICATE KEYS IN YOUR ARRAY
           'id' => 2

  );

so perhaps you should do array_push in both conditions (for the current example ofcourse), so you would get following structure:

$c = array(

          0 => array(
              'id' => 1,
              'size' => 'X5',
              'count' => 1,
           ),

          1 => array(
               'id'=>2,
               'size'=>'X3',
           ...

  );
0
On

Do this to set your cart instead:

$_SESSION['cart'][] = array("id" => $_GET['id'],"size" => $_POST['size'],"count" => $_POST['count']);

Then every cart item will be a sub-array of $_SESSION['cart']