EDIT
Now I can output the current product, but every time the form adds another item it gets overriden. I want to make the list incremental like this:
1. Banana 3 Units, Price 350 CRC
2. Yougurt 4 Units Price 2000 CRC
3. etc etc
4. etc
The current output only shows the last added item.
This is the script:
<?php
session_start();
//Getting the list
$list= $_SESSION['list'];
//stock
$products = array(
'Pineaple' => 500, 'Banana' => 50, 'Mango' => 150,
'Milk' => 500, 'Coffe' => 1200, 'Butter' => 300,
'Bread' => 450, 'Juice' => 780, 'Peanuts' => 800,
'Yogurt' => 450, 'Beer' => 550, 'Wine' => 2500,
);
//Saving the stuff
$_SESSION['list'] = array(
'item' => ($_POST['product']),
'quantity' => ($_POST['quantity']),
'code' => ($_POST['code']),
);
//price
$price = $products[($_SESSION['list']['item'])] * $_SESSION['list']['quantity'];
$_SESSION['list']['price'] = $price;
//listing
echo "<b>SHOPPIGN LIST</b></br>";
foreach($_SESSION as $key => $item)
{
echo $key[''], '. ', $item['item'], ' ', $item['quantity'], ' units: ', $item['price'];
}
//Recycling list
$_SESSION['list'] = $list;
echo "</br> <a href='index.html'>Return to index</a> </br>";
//Printing session
var_dump($_SESSION);
?>
This line is your issue.
You’re setting the variable you’re trying to iterate across to be an array with a single entry in it, not to mention the fact that
$priceisn’t going to be a nested array, which is why trying to getitem['key']is failing (as in'price'will be your key and$pricewill be your item in your foreach).EDIT:
I believe, from a second quick glance you’re actually intending to do this:
correct me if I’m wrong.
EDIT 2:
Actually, looking again, I’m not quite sure I understand your structure for your
$_SESSION['list']variable. It looks like you want something like:but what you have (from the fact you reference
$_SESSION['list']['item']) is only:you actually have multiple problems here. First try and deal with the bad structure of
$_SESSION['list']then try and deal with the foreach loop.EDIT 3:
I still don’t think you’re quite understanding what I mean, so I’m just going to fix the code to be what I’m pretty sure you’re looking for…
I’m pretty sure what you’re going for looks something like this: