I'm creating a shopping cart. Only with session variables. I want something simple, no database, it is only for initial system (later that perhaps use database and logins)
I click in a product and use URL to add in SESSION variable
Exemple Product: Orange
Sent url
site.com/?page=buy&add=Orange&type=fruit
Then...
session_start();
//Create 'cart' if it doesn't already exist
if (!isset($_SESSION['SHOPPING_CART'])){ $_SESSION['SHOPPING_CART'] = array(); }
if (isset($_GET['add'])){
//Adding an Item
//Store it in a Array
$ITEM = array(
//Item name
'name' => $_GET['add'],
'type' => $_GET['tipo'],
//Item Price
);
For print, I use:
foreach ($_SESSION['SHOPPING_CART'] as $itemNumber => $item) {
echo $item['type'];
echo $item['name'];
}
But My problem is, when I print I see something like this: Fruit Orange Fruit Apple Fruir Banana
Someone can tell me how do I only appear once "Fruit". How do I comparison is already is repeated?
Example that I want: Fruit Orange Apple Banana
$itemType = "";
foreach ($_SESSION['SHOPPING_CART'] as $itemNumber => $item) {
if($itemType == $item['type']) {
// skip...don't print again
} else {
echo $item['type'];
}
echo $item['name'];
$itemType = $item['type'];
}
You'd need to add another level to the cart, eg
$_SESSION['SHOPPING_CART'][$_GET['tipo']][$_GET['add']]
so you'd end up with a nested array structure:
SHOPPING_CART -> fruit -> orange
-> fruit -> apple
-> vegetable -> pizza
$itemType = "";
foreach ($_SESSION['SHOPPING_CART'] as $itemNumber => $item) {
if($itemType == $item['type']) {
// skip...don't print again
} else {
echo $item['type'];
}
echo $item['name'];
$itemType = $item['type'];
}
Great!
however if I have a problem. If I add a fruit, then a food, then a fruit:
Print:
Fruit:
Banana
Banana
Food:
Meat x
Fruit:
Apple
However, it´s possible to not repeat the "banana" banana?
Print:
Fruit:
Banana
Apple
Food:
Meat x
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.