Storing multiple values in a $_SESSION variable with PHP

前端 未结 1 1536
灰色年华
灰色年华 2020-12-15 12:12

I\'m creating a site which has a shopping cart. I do not need any special functionality so I\'m creating the cart on my own rather than integrating any ready one. My product

相关标签:
1条回答
  • 2020-12-15 12:24

    Use the item ID as an array key, which holds an array of the other items:

    // Initialize the session
    session_start();
    
    // Parent array of all items, initialized if not already...
    if (!isset($_SESSION['items']) {
      $_SESSION['items'] = array();
    }
    
    // Add items based on item ID
    $_SESSION['items'][$itemID] = array('Quantity' => $quantity, 'Total' => $total);
    // Another item...
    $_SESSION['items'][$another_itemID] = array('Quantity' => $another_quantity, 'Total' => $another_total);
    // etc...
    

    And access them as:

    // For item 12345's quantity
    echo $_SESSION['items'][12345]['Quantity'];
    
    // Add 1 to quantity for item 54321
    $_SESSION['items'][54321]['Quantity']++;
    
    0 讨论(0)
提交回复
热议问题