简体   繁体   中英

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?

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):

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. Later you can iterate over the products like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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