njhelloworld njhelloworld - 1 year ago 39
JSON Question

Array for Json Month sum of column

I am currently creating a json file for my chart, now.I wanted to have an output like


[{"ts":"September","ph":23},{"ts":"July","ph":13}]


where September ph is equivalent to values: 10,8,2,3 and July ph is equivalent to 10 and 3 from my database.

But the reality is I only got this output only


[{"ts":"September","ph":23}]


which came from the code below. I wanted to add the july ph added values.

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

}


Please!! I need your help!!!

Kam Kam
Answer Source

You can do something like that. That will create an array entry for each month of your mysql query result and sum it.

// 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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download