0

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'];
    }

But My problem is, when I print I see something like this:

Fruit:
  Orange
  Orange
  Apple 
Food
 Meat

Someone can tell me how do I only appear once one "Fruit". How do I comparison is already is repeated? Only 1 orange.

Fruit:
      Orange
      Apple 
    Food
     Meat
4

2 回答 2

0

使用array_unique()PHP的功能。手册在这里

或者你可以使用记忆技术来检查这个项目是否已经在这个循环的前面看到过。

$itemType = ""; 
foreach ($_SESSION['SHOPPING_CART'] as $itemNumber => $item) {
 if($itemType == $item['type']) {
   // skip...don't print again
 } else { 
    echo $item['type']; 
 }
 if(!isset($memo[$item['name']]))  
 echo $item['name']; 
 $memo[$item['name']] = 1;
 $itemType = $item['type'];
}
于 2013-07-29T09:22:11.927 回答
-1

只需使用 array_unique

foreach (array_unique($_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'];
    }
于 2013-07-29T09:27:37.017 回答