temel alışveriş sepeti script alt toplam ve toplam hesaplama

2 Cevap

Bir dizide saklanan değerlerin bir dizi bir alt toplam ve toplam hesaplamak için çalışıyor Im bir mysql veritabanı döndü.

Bu ne i i thusfar var

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

$ Içeriğini bir dizi içerir [name] => super [price] => 65.87 [quantity] => 25

Yani ben miktara göre fiyat çarpmak gerekir, ve sonra döngü sonra (ürün başına) bu alt toplamını almak ve toplam eklemek

2 Cevap

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

Sonra $ subtotal dizide $ toplam ve her öğe için toplam fiyat var

Ben toplamda ve alt toplam için ne anlama geldiğini emin değilim. Ben subtotal bir öğe kez onun miktar fiyat olduğunu varsayalım.

Toplam için ben size kırmızı yazdırmak alt toplamı niyetinde varsayalım.

Sizin kod haline:

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