以下是我的PHP代码:
<?php
echo "<h1>test</h1>";
echo "<table border = '1' width = '50%'>\n";
echo "<tr>";
echo "<th>date</th>";
echo "<th>temperature</th>";
//get data from file
$fileName = 'sensor.csv';
$file = fopen($fileName,"r");
//while not to end of file
while (!feof($file) )
{
while (($csv_line = fgetcsv($file)) !== FALSE)
{
$date_format = strtotime($csv_line[0]);
//print_r($csv_line);
echo "<tr>"; //beginning new row of record
echo "<td>" . date("Y-m-d", $date_format)."</td>";
echo "<td>" . $csv_line[2]."</td>";
echo "</tr>"; //new row
}
echo "</table>\n";
}
?>
以下是当前输出
date temperature
2015-07-20 22.7
2015-07-20 22.7
2015-07-20 22.8
2015-07-19 32.8
2015-07-19 31.9
2015-07-19 32.8
2015-07-19 32.8
2015-07-18 29.1
2015-07-18 28.8
2015-07-18 29.7
2015-07-18 29.9
2015-07-18 29.4
2015-07-18 29.8
2015-07-16 26.4
2015-07-16 25.9
2015-07-16 24.7
2015-07-16 24.9
2015-07-16 25
2015-07-16 26.4
2015-07-16 27
2015-07-16 26.1
2015-07-16 26
我希望它是这样的:
date temperature
2015-07-20 average temperature of each day
2015-07-19 average temperature of each day
2015-07-18 average temperature of each day
2015-07-16 average temperature of each day
答案 0 :(得分:0)
试
SELECT date, AVG(temperature) as AvgTemp
FROM TableName
GROUP BY date
答案 1 :(得分:0)
这是编辑过的代码,因为我无法检查它可能包含错误
<?php
echo "<h1>test</h1>";
echo "<table border = '1' width = '50%'>\n";
echo "<tr>";
echo "<th>date</th>";
echo "<th>temperature</th>";
//get data from file
$fileName = 'sensor.csv';
$file = fopen($fileName,"r");
while (!feof($file)) {
$cs = fgetcsv($file);
$last_date = $cs[0][0];
$sum_temp = 0;
$count = 0;
$csv_line = array();
$firsttime = true;
do {
if (!$firsttime) {
$date_format = strtotime($csv_line[0]);
$temp = $csv_line[2];
} else {
$date_format = $last_date;
$temp = $cs[0][2];
}
if ($date_format == $last_date) {
$sum_temp += $temp; // Combine tempratures
$count++;
} else {
$avg_temp = $sum_temp / $count; // Get the average temprature
echo "<tr>"; //beginning new row of record
echo "<td>" . date("Y-m-d", $last_date) ."</td>";
echo "<td>" . $avg_temp ."</td>";
echo "</tr>"; //new row
$sum_temp = 0;
$count = 0;
}
$firsttime = false;
$last_date = $date_format;
} while(($csv_line = fgetcsv($file)) !== FALSE);
echo "</table>\n";
}
?>