Im trying to calculate a subtotal and a total from a series of values stored in an array returned from a mysql database.
this i what i have thusfar
while($row = mysql_fetch_array($cart)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
$contents = unserialize($row['contents']);
foreach( $contents as $key => $value){
if($key == "price"){$subtotal = $subtotal+$value;}
echo "$key : $value <br />";
}
echo "<br><br><br>";
}
echo "<font color=red>SubTotal $subtotal</font>";
$contents contains an array [name] => super [price] => 65.87 [quantity] => 25
So i need to multiply the price by quantity, and then take that subtotal (per ite开发者_Python百科m) and add it in total after the loop
foreach( $contents as $key => $value)
{
if($key == "price") $total = $total+$value;
if($key == "name")
{
if(!isset($subtotal[$key])) $subtotal[$key] = 0;
$subtotal[$key] = $subtotal[$key] + $value;
}
}
Then you have total price in $total and for each individual item in $subtotal array
I'm not sure what you mean for total and subtotal. I assume that subtotal is the price of an item times his quantity.
For Total I assume you intend the subtotal you print in red.
Your code become:
$total=0;
while($row = mysql_fetch_array($cart)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
$contents = unserialize($row['contents']);
$contents['subtotal'] = $contents['price']*$contents['quantity'];
foreach($contents as $key => $value){echo "$key : $value <br />"; }
$total +=$content['subtotal'];
}
echo "<font color=red>Total: $total</font>";
If the formatting is not mandatory I would use a slight different solution for formatting the output. (you should check the printf format string placeholder syntax)
$billLine = "%s (%0.2f x %d): %0.2f<br /><br /><br />";
$total=0;
while($row = mysql_fetch_array($cart)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
$contents = unserialize($row['contents']);
$subtotal = $contents['price']*$contents['quantity'];
printf($billLine, $contents['name'],
$contents['quantity'],
$contents['price'],
$subtotal);
$total +=$subtotal;
}
echo "<font color=red>Total: $total</font>";
精彩评论