问题
I'm trying to store items in a shopping cart from user input in a form using sessions. This is my code to store the items in the cart.
//Create cart if it doesn't already exist
if (!isset($_SESSION['Cart']))
{
$_SESSION['Cart'] = array();
}
//Add an item only if required movie info needed
if(isset($_POST['Cinema']) && isset($_POST['Day']) && isset($_POST['Time']) && isset($_POST['Quantity']) && isset($_POST['Price']))
{
$ITEM = array(
'Cinema' => $_POST['Cinema'],
'Day' => $_POST['Day'],
'Time' => $_POST['Time'],
'Quantity' => $_POST['Quantity'],
'Price' => $_POST['Price']
);
//Add this item to the cart
$_SESSION['Cart'][] = $ITEM;
}
However, I keep getting this error :
Fatal error: [] operator not supported for strings in Line 31.
Lines 31 is : $_SESSION['Cart'][] = $ITEM;
Is my syntax wrong?
回答1:
As of the moment, $_SESSION['Cart']
is a string, not an array - and you can't push to a string as if you would push to an array.
You need to clear the session using session_unset(), then reset $_SESSION['Cart']
to be an array.
来源:https://stackoverflow.com/questions/26292717/fatal-error-operator-not-supported-for-strings-error-shopping-cart