2009-11-23 132 views
0

我试图从mysql数据库返回的数组中存储的一系列值中计算小计和总计。从基本购物车脚本计算小计和总计

这个我什么,我都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>"; 

$内容包含数组[name] => super [price] => 65.87 [quantity] => 25

所以我需要通过数量乘以价格,然后采取小计(每件),并将其添加在循环

+1

您selfproviding的步骤进行总量计算;)只要把过程或函数的步骤就大功告成了,你应该ofcourse跟踪小计: )但是,通过在循环外部设置var(例如$ carttotal)并将每行小计(qty * price)添加到$ carttotal可以轻松完成。 – Ben 2009-11-23 10:34:08

回答

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

后总那么你有总价格在$总量以及在$次全阵列中的每个单独的项目

+0

数量如何? – Eineki 2009-11-23 10:57:07

+0

foreach($ subtotal as $ key => $ value) { $ count [$ key] = count($ subtotal [$ key]); $ totalCount = $ totalCount + $ count [$ key]; } 然后你将有一个数组,每个项目数和总数在$ totalCount – dfilkovi 2009-11-23 11:31:23

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>";