Oscar C. Oscar C. - 2 months ago 6x
JSON Question

calculate avg return "0" PHP

I have MySQL with Float Values which are pressure parametters. I need to calculate average. But the code I make returns me average "empty" in my json response.

Here is the json response I get:

{"result":{"pressure":{"min":[{"Id":"2","presion":"0","Insertado":"2016-08-16 16:20:08"},{"Id":"5","presion":"0","Insertado":"2016-08-16 18:09:04"}],"max":[{"Id":"3","presion":"55","Insertado":"2016-08-16 16:22:14"}],"avg":[]},"last_entry":{"Id":"8","presion":"50","Insertado":"2016-08-16 18:28:45"}}}

As it shows. avg give empty!.

This is code in PHP

$press_values = get_press_values($json_object->result);

// get pressure result set with respected values
$press_result = get_press_result_set_from_values($json_object->result,$press_values);

// get latest entry
$latest_entry = get_latest_date_entry($json_object->result);

// Wrap results in an array
$output_result = array(
'pressure' => $press_result,
'last_entry' => $latest_entry


function get_press_values($result){

$min = -1;
$max = -1;
$avg = -1;

// get all pressure values
$pressures = array_map(function($result_item) {
return intval($result_item->presion);
}, $result);

$min = min($pressures);
$max = max($pressures);
$avg = intval(calculate_average($pressures));

return array(
'min' => $min,
'max' => $max,
'avg' => $avg



function get_press_result_set_from_values($array,$value){
$min_objs = array();
$max_objs = array();
$avg_objs = array();
foreach ($array as $item) {

if($item->presion == $value['min']){
$min_objs[] = $item;

if($item->presion == $value['max']){
$max_objs[] = $item;

if($item->presion == $value['avg']){
$avg_objs[] = $item;

return array(
'min' => $min_objs,
'max' => $max_objs,
'avg' => $avg_objs,


function calculate_average($arr) {
$total = 0;
$count = count($arr); //total numbers in array
foreach ($arr as $value) {
$total = $total + $value; // total value of array numbers
$average = ($total/$count); // get average value
return $average;



This part in your code:

if($item->presion == $value['avg']){
    $avg_objs[] = $item;

will only add an item if the presion perfectly matches the average, which can be very unlikely, depending on your data of course.

update: For example you have the values 50, 51, 54, 55. The average is 53. Your code will not find any $item->presion which is equal to 53, because the average doesn't need an item that has that value (in contrast to min and max).

You should check if you actually mean the median (which has to be determined in a different way ...).

update2: to get the average into your result, you have to change $avg_objs = array(); to $avg_objs = $value['avg'];. and remove the part from your code that I posted above.

Also, if you want your average to not be an integer, you should change the line

$average = ($total/$count);


$average = (float)$total / $count;

and remove the intval from:

$avg = intval(calculate_average($pressures));