2014-10-30 12 views
-3

我想根据数量添加所有产品价格。唯一的问题是每个项目都是根据用户选择随机添加的,然后可以将其调整为任意随机数量。PHP:总成本

尝试向商店中添加变量以将它们添加到一起的附加数组,但它没有采用QT ammount。

PHP:

<?php 

$total = 0; 

// Fetch Database 

$results->data_seek(0); 

foreach ($_SESSION['cart'] as $item => $quantity) { 

    $row = $results->fetch_assoc(); 

    $pId = $row['ProductID']; 
    $pName = $row['ProductName']; 
    $pImg = $row['ProductImg']; 
    $pPrice = $row['Price']; 
    $pInfo = $row['About']; 

    foreach ($quantity as $quantity) { 

     $priceA = array(); 

     $pushA = $pPrice * $quantity; 

     array_push($priceA, $pushA); 

     $bT = implode(",", $priceA); 

     $total += $priceA; 

    } 

?> 

标记

<div class="col"> 
     <img src="img/<?php echo $pImg; ?>"> 

     <h1><?php 
      echo $pName; 
     ?></h1> 

     <h2>$<?php 
      echo $pPrice; 
     ?></h2> 

     <h3>QT: <?php echo $quantity; ?> 
      <a href="addc.php?id=<?php echo $pId ?>">+</a> 
      <a href="rc.php?id=<?php echo $pId ?>">-</a></h3> 
    </div> 

    <?php } ?> 

    <div class="cpan"> 
     <div class="col2"> 
      <div class="allc"> 
       <h1>Your total: <?php echo ($total); ?></h1> 
      </div> 
     </div> 
    </div> 

PHP

// Add 1 QT 

$item = $_GET['id']; 
$quantity = 1; 

if(isset($_SESSION['cart'][$item])) { 
    $_SESSION['cart'][$item] += $quantity; 
} else { 
    $_SESSION['cart'][$item] = $quantity; 
} 


// Remove 1 QT 

$item = $_GET['id']; 
$quantity = 1; 

if(isset($_SESSION['cart'][$item])) { 
    $_SESSION['cart'][$item] -= $quantity; 
} else { 
    $_SESSION['cart'][$item] = $quantity; 
} 

enter image description here

+2

可以打印出'$ _SESSION [ '购物车']'? 'print_r($ _ SESSION ['cart']);' – Jono20201 2014-10-30 20:03:49

+0

是的,它是一个像这样设置的多维数组; $ _SESSION ['cart'] [$ item] = $ quantity;你可以用简单的+ =或 - =来增加或减少数量。 – Kris 2014-10-30 20:06:11

+1

精确数据的一个示例将帮助我在图像中添加 – 2014-10-30 20:09:56

回答

2

已解决。

  • 删除次要的foreach
  • 变量改为匹配...

PHP:

<?php 

    $total = 0; 

    // Fetch Database 

    $results->data_seek(0); 

    foreach ($_SESSION['cart'] as $item => $quantity) { 

     $row = $results->fetch_assoc(); 

     $pId = $row['ProductID']; 
     $pName = $row['ProductName']; 
     $pImg = $row['ProductImg']; 
     $pPrice = $row['Price']; 
     $pInfo = $row['About']; 


      $priceA = array(); 

      $pushA = $pPrice * $quantity; 

      array_push($priceA, $pushA); 

      $bT = implode(",", $priceA); 

      $total += $bT; // Change to $bT 

    ?>