I get a FORM POST and on the button pressed (submitted) there is a value (primary key) of the item in the database ($artid).
For each of these POSTs I try and add a new object value into an array mapped to a key set by $artid, so it should be unique. The array is added to a $_SESSION to get the same array out each time.
The first object is added fine, but other objects just overwrites the second position in the array. I need it to continue to grow.
Code:
if (!isset($_SESSION['itemArray'])) {
...
$cartArr = array();
$bookitem = new BookItem($artid, $qty, $price);
$cartArr[$artid] = $bookitem;
$_SESSION['itemArray'] = $cartArr;
foreach($cartArr as $key => $obj) { .... }
}
else {
$cartArr = $_SESSION['itemArray'];
if (array_key_exists($artid, $cartArr)) {
$cartArr[$artid]->quantity = $qty;
}
else {
$bookitem = new BookItem($artid, $qty, $price);
$cartArr[$artid] = $bookitem;
}
foreach($cartArr as $key => $obj) { ... }
}
Thanks in advance for any help!
It doesn’t look like your setting the Session array back once you add the new element. So the next time the page loads the new value wasn’t saved.
You have 2 options:
1) after your foreach set
$_SESSION['itemArray'] = $cartArr;this will save any changes (such as adding a new element) in session.2) Assign
$cartArrto be a reference to$_SESSION['itemArray']so that any changes made to$cartArrare actually made to$_SESSION['itemArray']You would do this by$cartArr =& $_SESSION['itemArray'];right after yourelse