我试图从存储在从mysql数据库返回的数组中的一系列值中计算小计和总数。
这就是我所拥有的如此
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包含数组[name] => super [price] => 65.87 [quantity] => 25
所以我需要将价格乘以数量,然后取出小计(每个项目)并在循环后将其加总
答案 0 :(得分:2)
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;
}
}
然后,总计价格为$ total和$ subtotal数组中的每个项目
答案 1 :(得分:1)
我不确定你对总数和小计的意思。我假设小计是一个项目的价格乘以他的数量。
总计我假设您打算以红色打印小计。
您的代码变为:
$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>";
如果格式不是强制性的,我会使用略有不同的解决方案 用于格式化输出。 (你应该查看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>";