calculate avg return "0" PHP
<p>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.</p>

<p>Here is the json response I get:</p>

<pre><code>{"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"}}}
</code></pre>

<p>As it shows. avg give empty!.</p>

<p>This is code in PHP</p>

<pre><code>$press_values = get_press_values($json_object-&gt;result);

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

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

    // Wrap results in an array
    $output_result = array(
        'pressure' =&gt; $press_result,
        'last_entry' =&gt; $latest_entry
    );
}
</code></pre>

<p>Then.</p>

<pre><code>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-&gt;presion);
}, $result);

if($pressures){
    $min = min($pressures);
    $max = max($pressures);
    $avg = intval(calculate_average($pressures));
}

return array(
    'min' =&gt; $min,
    'max' =&gt; $max,
    'avg' =&gt; $avg
);
</code></pre>

<p>}</p>

<p>Then:</p>

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

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

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

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

return array(
    'min' =&gt; $min_objs,
    'max' =&gt; $max_objs,
    'avg' =&gt; $avg_objs,
);
</code></pre>

<p>}
then:</p>

<pre><code>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;
</code></pre>

<p>}</p>