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

标签 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。我想添加这些项目数量以避免重复。我该怎么做?

最佳答案

我个人是按数组传递,或者在key上积累,然后浏览数组。
例如:

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

关于php - 如何添加具有相同值的查询行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22588899/

相关文章:

php - 将多个文本框条目添加到 mysql 数据库

mysql - MySQL 中何时使用单引号、双引号和反引号

mysql - Ubuntu:更改 mysql datadir 问题

PHP XML 错误 - 文档末尾有多余内容

php - UPS Rates API 提供低价

php - 如何在 Laravel 中高效地编写复杂业务逻辑的单元测试

php - 具有左右值的可嵌套树

php - 使用 NOT IN 将 SQL 转换为 Doctrine 2 Query Builder 或 DQL?

Mysql 查询过去 14 天的事件(每两周一次)

mysql - 如何使用查询构建器 laravel 在 leftjoin 期间加入子查询?