I know how to do that this way:
Code: Select all
$shoppingChart = array(
36 => 1,
334 =>2,
45 => 1,
);O should I just use 2d array?
Moderator: General Moderators
Code: Select all
$shoppingChart = array(
36 => 1,
334 =>2,
45 => 1,
);Code: Select all
<?php
$shoppingChart = array(
[0] => array (
'sku' => '36',
'quantity' => 1,
),
[1] => array (
'sku' => '334',
'quantity' => 2,
),
[2] => array (
'sku' => '45',
'quantity' => 1,
),
);
foreach ($shoppingChart as $n => $item) {
echo "$n. sku={$item['sku']}, quantity={$item['quantity']}<br/>\n";
}
?>Code: Select all
<?php
function AddItem(& $ShoppingCart, $ItemId, $Quantity)
{
// should check that
// a) $ShoppingCart is an array
// b) $Quantity is a number
if (true == isset($ShoppingCart[$ItemId]))
{
$ShoppingCart[$ItemId] += $Quantity;
}
else
{
$ShoppingCart[$ItemId] = $Quantity;
}
}
function RemoveItem(& $ShoppingCart, $ItemId, $Quantity)
{
// should check that
// a) $ShoppingCart is an array
// b) $Quantity is a number
if (true == isset($ShoppingCart[$ItemId]))
{
// Should check that there are at least $Quantity items
// in array before removing them, otherwise issue some
// kind of error
$ShoppingCart[$ItemId] -= $Quantity;
}
}
$shopping_cart = array();
echo '<br />Start<br />';
print_r ($shopping_cart);
AddItem ($shopping_cart, 'Item1', 25);
AddItem ($shopping_cart, 'Item5', 5);
AddItem ($shopping_cart, 'Item1', 10);
echo '<br />After Add<br />';
print_r ($shopping_cart);
RemoveItem ($shopping_cart, 'Item1', 4);
echo '<br />After Remove<br />';
print_r ($shopping_cart);
?>Code: Select all
//if want to empty the schart...
if ( $_GET['action'] == "deleteAll" )
{
unset($_SESSION['shoppingChart']);
}
//if want to add or remove from the chart
elseif($_GET['action']=="addToChart" && isset($_GET['itemID']))
{
$itemID = $_GET['itemID'];
//array_push($shoppingChart,array('id' =>$itemID,'count'=>1));
if(isset($_SESSION['shoppingChart']))
{
$shoppingChart = $_SESSION['shoppingChart'];
}
else
{
$shoppingChart = array();
}
static $de;
foreach ($shoppingChart as $index => $val)
{
if($val['id']==$itemID)
{
$shoppingChart[$index]=array('id' => $itemID,'count'=>$val['count']+1);
$de = 1;
break;
}
}
if($de!=1) array_push($shoppingChart,array('id' =>$itemID,'count'=>1));
}
elseif($_GET['action']=="removeItem" && isset($_GET['itemID']))
{
$itemID = $_GET['itemID'];
//array_push($shoppingChart,array('id' =>$itemID,'count'=>1));
if(isset($_SESSION['shoppingChart']))
{
$shoppingChart = $_SESSION['shoppingChart'];
}
else
{
$shoppingChart = array();
}
foreach ($shoppingChart as $index => $val)
{
if($val['id']==$itemID)
{
$shoppingChart[$index]=array('id' => $itemID,'count'=>0);
break;
}
}
}
$_SESSION['shoppingChart'] = $shoppingChart;