Mysql导出到csv与组总计

时间:2017-10-20 22:06:34

标签: php mysql csv

我想将我的记录从mysql导出到csv,我想在生成的csv中实现这个输出:

Date        |   Name    |   Score
-------------------------------------
10/01/17    |   John    |   1
10/02/17    |   John    |   3
10/03/17    |   John    |   12

Total                       16
-------------------------------------
10/01/17    |   Peter   |   4
10/02/17    |   Peter   |   17
10/03/17    |   Peter   |   3

Total                       24

我当前的代码正在运行但没有总行。请参阅下面的我当前的代码。

function toCsv($data) {
    $fp = fopen('report.csv', 'w');

    foreach ($data as $fields) {
        fputcsv($fp, $fields);
    }

    fclose($fp);
}

$arr = ['Data', 'Name', 'Score'];

while($row = $results->fetch_assoc()) {
    $data = [
        $row['date'],
        $row['name'],
        $row['score']
    ];

    $arr[] = $data;
}
toCsv($arr);

2 个答案:

答案 0 :(得分:2)

在您获取每一行时,将分数添加到$total变量。

此外,$arr的初始值应该是包含标题作为第二个数组的数组。

function toCsv($data) {
    $fp = fopen('report.csv', 'w');

    foreach ($data as $fields) {
        fputcsv($fp, $fields);
    }

    fclose($fp);
}

$arr = [['Date', 'Name', 'Score']];
$total = 0;
$last_name = null;
while($row = $results->fetch_assoc()) {
    if ($last_name && $last_name != $row['name']) {
        // Name has changed, add a total row for previous name
        $arr[] = ['Total', $total];
        $total = 0;
        $last_name = $row['name'];
    }
    $data = [
        $row['date'],
        $row['name'],
        $row['score']
    ];

    $arr[] = $data;
    $total += $row['score']
}
// Add total row for last name
$arr[] = ["Total", $total];
toCsv($arr);

答案 1 :(得分:1)

您需要在末尾添加包含总数的新数组

//.........
//.........
$total = 0;
$arr = ['Data', 'Name', 'Score'];
while($row = $results->fetch_assoc()) {
    $data = [
        $row['date'],
        $row['name'],
        $row['score']
    ];
    $total = $total+$row['score'];
    $arr[] = $data;
}
$total_arr = array(
    "Total",
    "-",
    $total
);
$arr[] = $total_arr;
toCsv($arr);