Jump to content

multidimensional array can't comprehend


Recommended Posts

Hey guys I am trying to make a simple shopping cart but I can't seem to wrap my head around this.


I have $_SESSION['cart'] as an array and I can add an item to it and then echo specific elements of the item like so


echo $_SESSION['cart']['0']['Name'];


I can not seem to figure out how to add a second item to the array so I can do something like


echo $_SESSION['cart']['1']['Name'];


and it will echo the second item that I 'added' to my cart?


Thanks I hope that makes sense.

Link to comment
Share on other sites

Here is part 1 of a series of youtube videos where the guy goes through everything you need to create a shopping cart. He uses multi arrays too.


I have learnt all my php from this dude, he's very good. You can watch the whole series and get a firm grasp on everything, or you can just find the video where he talks about the multi arrays :).





Link to comment
Share on other sites

the multidimensional array ah yes


$_SESSION['cart'] = array();

$_SESSION['cart']['0']['Name'] = 'product 1';

$_SESSION['cart']['1']['Name'] = 'product 2';

$nextnum = count($_SESSION['cart']) + 1;

$_SESSION['cart'][$nextnum]['Name'] = 'product 3';



so by using the count function you always know where you are up to in the array, then add 1 for the next 'key' to assign it's 'value'

Link to comment
Share on other sites

Hey so i'm not sure what I'm doing wrong here.


for some reason when I try to add a new product the $nextnum var wont increase so it just keeps overwritting the first product.


I have this and then a form to "add to cart" or submit it via post



$_SESSION['cart'] = array();

$nextnum = count($_SESSION['cart']) + 1;

echo $nextnum;

$_SESSION['cart'][$nextnum]['name'] = $_POST['name'];
$_SESSION['cart'][$nextnum]['id'] = $_POST['id'];
$_SESSION['cart'][$nextnum]['price'] = $_POST['price'];
$_SESSION['cart'][$nextnum]['size'] = $_POST['size'];
$_SESSION['cart'][$nextnum]['color'] = $_POST['color'];



Link to comment
Share on other sites

ok well i figured that out out I have a new question lol


I can not seem to get the number of that array for example


say there are 3 things in the cart array


$count = count($_SESSION['cart']);
echo $_SESSION['cart'][$i];


instead of listing 0,1,2  it just says Array,Array,Array


why is that?

Link to comment
Share on other sites


This topic is now archived and is closed to further replies.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.