-->

PHP, Associative arrays with sessions [duplicate]

2019-08-08 19:38发布

问题:

This question already has an answer here:

  • PHP parse/syntax errors; and how to solve them? 17 answers

I'm just looking for a push in the right direction here. I am trying to create an associate array using a session. The intent is that when a user adds an item to the cart, the item and quantity is added to the array. I am getting a "Parse error: syntax error, unexpected T_DOUBLE_ARROW" error on line 13. I think I am just going about it wrong.

<?php
$action = $_GET['action'];
$itemID = $_GET['itemID'];
$qty = $_GET['quantity'];
$msg;
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart']['itemID'] = ('123' => 0, '456' => 0, '589' => 0, '101' => 0);
}
$cart = $_SESSION['cart'];
if ($action == 'add') {
/*  if (!in_array($cart, $itemID) {  // Add item to array
        $cart[$itemID]
        //array_push($cart, $itemID => $qty);
    }
    else { // Increase quantity */
        $_SESSION['cart'][$itemID] = $q;
        $v = $q + $qty;
        $_SESSION['cart'][$itemID] = $v;
//  }
    $msg = $qty.' of item # '.$itemID.' has been added to your cart.';
}
else { // remove from cart
    unset($_SESSION['cart'][$itemID]);
    $msg = $qty.' of item # '.$itemID.' has been removed to your cart.';
}
echo $msg; ?>

Error occurs in first if(!isset($SESSION['cart']) statement upon creation.

I was getting an error when I had the array_push enabled as well, but I do not recall what it was.

Basically the function is this - SESSION array is created when user add item to cart (always quantity one at this time). When item is added, the item number and quantity is added to the array. Add another item, it is added. Add the same item, quantity increases by one. Remove an item .. so on and so forth.

Hopefully you get the idea. I've got the bones written and am in the test/troubleshoot phase. As I've said, I think I am creating the array wrong. I'd like to create the array empty and add items as needed, but I've tried a few different ways trying to at least get it working, the one shown above is the most recent. Again, obviously approaching the SESSION associative array all wrong.

Any advice would be greatly appreciated! Thank you in advance.

回答1:

Looks like you have an error at line 7 change it to

$_SESSION['cart']['itemID'] = array('123' => 0, '456' => 0, '589' => 0, '101' => 0);

you can also check how to define a array



回答2:

You're missing Array

if (!isset($_SESSION['cart'])) {
    $_SESSION['cart']['itemID'] = Array('123' => 0, '456' => 0, '589' => 0, '101' => 0);
}