我正在为我的图表创建一个json文件,现在。我希望有一个像
这样的输出[{ “TS”: “九月”, “PH”:23},{ “TS”: “七月”, “PH”:13}]
其中9月ph等于值:10,8,2,3和7月ph相当于我数据库中的10和3。
但实际情况是我只得到了这个输出
[{“ts”:“九月”,“ph”:23}]
来自下面的代码。我想添加7月添加的ph值。
$sumsep = 0;
$sumjul = 0;
while($row = mysqli_fetch_array($result))
{
/* Push the results in our array */
// $point = array("ts" => date('m',strtotime($row['time_stamp'])) ,"ph" => $row['ph']);
$monthNum = date('m',strtotime($row['time_stamp']));
$dateObj = DateTime::createFromFormat('!m', $monthNum);
$monthName = $dateObj->format('F');
if(($monthName=="September")){
$data_points = array();
$sumsep += $row['ph'];
$point = array("ts" => $monthName,"ph" => $sumsep);
array_push($data_points,$point);
}
}
请!!我需要你的帮助!!!
答案 0 :(得分:1)
你可以做那样的事情。这将为您的mysql查询结果的每个月创建一个数组条目并对其求和。
// Init your data point by month array
$data_points = array();
while($row = mysqli_fetch_array($result)) {
$monthNum = date('m',strtotime($row['time_stamp']));
$dateObj = DateTime::createFromFormat('!m', $monthNum);
$monthName = $dateObj->format('F');
// Check if already a result for this month
if (array_key_exists($monthName, $data_points)) {
// Sum you pH
$data_points[$monthName]->ph += $row['ph'];
} else {
// Create first pH entry for month
$data_points[$monthName] = new stdClass();
$data_points[$monthName]->ph = $row['ph'];
$data_points[$monthName]->ts = $monthName;
}
}
// Extract only result (months name as key not needed)
echo json_encode(array_values($data_points));