cristi2050 cristi2050 - 6 months ago 9
MySQL Question

How to make an average of array values

I have a database with multiple records. It is structured like this:

["data"]=>
array(5) {
[1]=>
[2]=>
array(11) {
[0]=>
string(1) "0"
[1]=>
string(8) "25000000"
[2]=>
string(3) "day"
[3]=>
string(5) "0.00%"
[4]=>
string(9) "404049904"
[5]=>
string(1) "0"
[6]=>
string(5) "0.00%"
[7]=>
string(1) "0"
[8]=>
string(1) "0"
[9]=>
string(1) "0"
[10]=>
string(3) "0.0"
}


I need to fetch the 8th record and I do this by using

public static function($data)
{
$array = [];
$path = $data->data[2];
foreach($path as $key => $item)
if($key > 1)
{
$array[] = [$item->data[8]];
}

return json_encode($array);
}


This foreach takes all the 8th values from the array but I need to display a single number which is the average of all the 8th values. How can I do this?

Answer

Because you put your value into a new array, you can not use array_sum to sum the values, so you should store it.

$sum = 0;
foreach($path as $key => $item)
   if($key > 1)   {
      $array[] = [$item->data[8]];
      $sum += $item->data[8];
   }
}
$avg = ($sum / count($array); //the average
var_dump($avg);

If is it possible, just put it as a value:

$array[] = $item->data[8];  //no wrapping []

In this case, you can use $avg = array_sum($array) / count($array);