php导出csv我要总结价格列

时间:2017-09-07 13:00:39

标签: php mysql csv

我有桌子,有项目,desc,价格。 当我作为csv导出时,我想要将价格列相加并放入最后一行,如子总计。 csv生成了很好..我需要总结价格列。

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=' . $type . '-' . date('Y-m-d') . '.csv');
    $output = fopen('php://output', 'w');


     foreach ($price_list as $car) {
        $i++;
        $rows[$i][id] = $car->id;
        $text = $car->item;
        $rows[$i][des]=$car->des;
        $rows[$i][text] = preg_replace('/\s+/S', " ", $text);
        $rows[$i][price]=$car->price;
        $rows[$i][stocks]=$car->stocks;

        $rows[$i][edited_dt] = $car->edited_dt;


    }




    foreach ($rows as $row) {
        fputcsv($output, $row);
    }

//查询 选择id,p_type,item,des,price,price_unit,stocks,stocks_unit,created_dt,created_by,edited_dt                 来自price_list,其中state = 1
                由id desc命令

3 个答案:

答案 0 :(得分:0)

在循环之前设置$total = 0;变量。在循环内,添加$total += $car->price;。然后在循环后添加最后一行。

答案 1 :(得分:0)

在循环中添加sum然后在for循环外添加包含sum行

的新列
$price_sum = 0;
foreach ($price_list as $car) {
        $i++;
        $rows[$i][id] = $car->id;
        $text = $car->item;
        $rows[$i][des]=$car->des;
        $rows[$i][text] = preg_replace('/\s+/S', " ", $text);
        $rows[$i][price]=$car->price;
        $price_sum += $car->price;; //sum  price here
        $rows[$i][stocks]=$car->stocks;

        $rows[$i][edited_dt] = $car->edited_dt;


    }
  $i++;
       $rows[$i][id] = "";
        $rows[$i][des]="";
        $rows[$i][text] ="";
        $rows[$i][price]=$price_sum; //add sum here
        $rows[$i][stocks]="";
        $rows[$i][edited_dt] ="";




    foreach ($rows as $row) {
        fputcsv($output, $row);
    }

答案 2 :(得分:0)

对于您的问题,实际上有一个纯粹的MySQL解决方案,假设您不想直接在PHP代码中进行任何聚合。请考虑以下查询:

SELECT
    id, p_type, item, des, price, price_unit, stocks, stocks_unit, creat‌​ed_dt,
    created_by, edi‌​ted_dt,
    SUM(price) AS total_price
FROM price_list
WHERE state = 1
GROUP BY
    id, p_type, item, des, price, price_unit, stocks, stocks_unit, creat‌​ed_dt,
    created_by, edi‌​ted_dt
WITH ROLLUP
HAVING
    (p_type IS NOT NULL AND item       IS NOT NULL AND des IS NOT NULL AND
     price  IS NOT NULL AND price_unit IS NOT NULL AND stocks IS NOT NULL AND
     stocks_unit IS NULL AND created_dt IS NULL AND created_by IS NOT NULL AND
     edited_dt IS NOT NULL) OR
     id IS NULL;

只需迭代此结果集,当您点击最后一条记录时,只需访问total_price列,该列将是价格的总和。除了它是结果集中的最后一条记录之外,此记录的标记是其他而不是total_price的任何列都是null

这是一个简化演示的链接,展示了整个表格的汇总技巧如何运作:

Demo