Reputation: 51
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:
$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'];
}
however, I have a problem. If I add a fruit, then a food, then a fruit:
Print:
Fruit:
Banana
Banana
Food:
Meat
Fruit:
Apple
However, it´s possible to not repeat the "banana" banana?
Print:
Fruit:
Banana
Apple
Food:
Meat x
Upvotes: 0
Views: 627
Reputation: 410
array_unique
— Removes duplicate values from an array
http://php.net/manual/en/function.array-unique.php
Example:
$items = array(
'key1' => 'orange',
'key2' => 'banana',
'key4' => 'orange',
'key5' => 'lemon',
);
// first print_r
print_r($items);
$items = array_unique($items);
// second print_r
print_r($items);
Output of the first print_r:
Array
(
[key1] => orange
[key2] => banana
[key4] => orange
[key5] => lemon
)
Output of the second print_r:
Array
(
[key1] => orange
[key2] => banana
[key5] => lemon
)
Upvotes: 1