使用 PHP 在 $_SESSION 变量中存储多个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8964480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 05:51:43  来源:igfitidea点击:

Storing multiple values in a $_SESSION variable with PHP

phpsessionshopping-cart

提问by cycero

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 products do not have a predefined price in the database. The price is being generated dynamically based on the values entered by a user on the product page. So, the user chooses some specifications, enters the quantity and I get the following values:

我正在创建一个有购物车的网站。我不需要任何特殊功能,所以我自己创建购物车,而不是集成任何现成的。我的产品在数据库中没有预定义的价格。价格是根据用户在产品页面上输入的值动态生成的。所以,用户选择一些规格,输入数量,我得到以下值:

Item ID
Quantity
Total price

商品编号
数量
总价

I need to store those values in the $_SESSION variable and then loop over it when needed to get the results and print them in the shopping cart. The problem is that there are a lot of products and I need to store all those values (Quantity, Total Price) distinctively for the chosen product. That said, how do I store Item ID, Quantity and Total price in the $_SESSION variable and associate those values with each other?

我需要将这些值存储在 $_SESSION 变量中,然后在需要时循环遍历它以获取结果并将它们打印在购物车中。问题是有很多产品,我需要为所选产品分别存储所有这些值(数量、总价)。也就是说,如何在 $_SESSION 变量中存储项目 ID、数量和总价并将这些值相互关联?

Thanks for helping.

谢谢你的帮助。

EDIT: My code implementing Michael's suggestions:

编辑:我的代码实现迈克尔的建议:

$itemid = $db->escape($_POST['productid']);
    $itemquantity = $db->escape($_POST['itemquantity']);
    $totalprice = $db->escape($_POST['totalprice']);

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

    $_SESSION['items'][$itemid] = array('Quantity' => $itemquantity, 'Total' => $totalprice);

    var_dump($_SESSION);

回答by Michael Berkowski

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

使用项目 ID 作为数组键,其中包含其他项目的数组:

// 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']++;