如何添加具有相同值的查询行?

时间:2014-03-23 09:08:02

标签: php mysql

我是PHP的新手。我有一张存储所购买交易的表格。我将总结两个日期之间发生的交易。例如:2014-03-21至2014-03-23 我把它放在fpdf :)中

这是我的疑问:

<?php

$query = "SELECT * FROM tbl_items INNER JOIN tbl_receipts ON tbl_items.item_id=tbl_receipts.item_id WHERE receiptdate >= '$sdate' && receiptdate <='$ldate'  ORDER BY tbl_items.item_id";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);

$addtotal = 0;
$counter = 1;
if (mysql_num_rows($result) != 0) {
    while ($row = mysql_fetch_assoc($result)) {
        $totaladd = $row['quantity_bought'] * $row['itemquantity_price'];
        $item = $row['item_description'];
        $num = $row['quantity_bought'];
        $pdf->Cell(15, 13, '', 0, 0, 'C');
        $pdf->Cell(15, 6, $counter, 1, 0, 'R');
        $pdf->Cell(60, 6, $row['item_description'], 1, 0, 'L');
        $pdf->Cell(20, 6, $row['quantity_bought'], 1, 0, 'R');
        $pdf->Cell(30, 6, $row['itemquantity_price'], 1, 0, 'R');
        $pdf->Cell(30, 6, "$totaladd.00", 1, 0, 'R');
        $pdf->Ln(6);
        $addtotal = $addtotal + $totaladd;
        $counter++;
    }
}
$pdf->Cell(15, 15, '', 0, 0, 'C');
$pdf->Cell(15, 6, '', 1, 0, 'R');
$pdf->Cell(60, 6, 'SUB-TOTAL', 1, 0, 'L');
$pdf->Cell(20, 6, '', 1, 0, 'R');
$pdf->Cell(30, 6, '', 1, 0, 'R');
$pdf->Cell(30, 6, "$addtotal.00", 1, 0, 'R');

$pdf->Ln(4);
?>

但是,总结之后,我有多行用于具有相同item_description的项目。我想添加这些项目数量以避免重复。我该怎么做?

1 个答案:

答案 0 :(得分:0)

就个人而言,我通过数组,或者我在键上累积,然后我浏览数组。
例如:

$array = array();
while($row = mysql_fetch_assoc($result)){
     $array[$row['item_description']]['quantity_bought'] = $row['quantity_bought'];
     $array[$row['item_description']]['itemquantity_price'] = $row['itemquantity_price'];
     ...   

}

foreach($array as $item_description => $array_detail){
     $item = $item_description;
     foreach($array_detail as $key => $value){
            if ($key == 'quantity_bought')  $num = $value;
            ...
        }
    }