简体   繁体   English

如何在会话中存储相同的值?

[英]How do I store the same values in a session?

I'm building a checkout system, and I'm trying to add products to a session variable. 我正在建立一个结账系统,我正在尝试将产品添加到会话变量中。 But I'm stuck on how I should save them. 但我仍然坚持要如何拯救他们。 How can I save for example 5 products? 如何保存例如5种产品?

I try to use something like this, but that doesn't work: 我尝试使用这样的东西,但这不起作用:

$_SESSION['cart']['productIds']['id'] .= $_POST['productid'];
$_SESSION['cart']['productPrices']['price'] .= $_POST['price']; 

The output is something like this (twice a product with id 2 and price 20): 输出是这样的(产品的两倍,ID为2,价格为20):

Array ( [productIds] => Array ( [id] => 22 ) [productPrices] => Array( [price] => 2020 )

I would like it to be saved as an array, what's the best approach for this? 我希望将它保存为数组,这是最好的方法吗?

You should treat the session variable as an array instead of string. 您应该将会话变量视为数组而不是字符串。 Append to it using the [] operator: 使用[]运算符附加到它:

$_SESSION['cart']['products'][] = array(
    'id' => $_POST['productid'],
    'price' => $_POST['price'],
);

You can also use array_push() if you want. 如果需要,您也可以使用array_push() Later you can iterate over the products like: 稍后您可以迭代以下产品:

foreach ($_SESSION['cart']['products'] as $product) {
    echo $product['id'], ': ', $product['price'], "\n";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM