2009-11-23 2 views
0

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

$ 내용 thusfar [name] => super [price] => 65.87 [quantity] => 25

그래서 내가 수량에 의해 가격을 곱하면, 다음 (항목 당)이 합계를 가지고 그것을 추가 할 필요가 배열을 포함 내가 무엇을 루프

+1

당신은 총을 계산하기 위해 수행하는 단계에 selfproviding된다 (당신은이 printf format string placeholder syntax가 확인해야합니다)) 그러나 이것은 루프 외부에 var (예 : $ carttotal)를 설정하고 행당 소계 (qty * price)를 $ carttotal에 추가하여 쉽게 수행 할 수 있습니다. – Ben

답변

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

+0

foreach ($ 부분합 $ key => $ 값) { $ count [$ key] = count ($ subtotal [$ key]); $ totalCount = $ totalCount + $ count [$ key]; } 각 항목 수와 총 개수가 $ totalCount 인 배열이 있습니다. – dfilkovi

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

경우 I 출력 포맷에 대해 약간 다른 솔루션 을 사용합니다. :) 그냥 프로 시저 또는 함수에서 해당 단계를 놓고 작업을 완료, 당신은 소계를 추적 당연히 유지해야한다

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