0

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?

2
  • sum($array) / count($array) Commented Jun 3, 2016 at 9:51
  • the problem is, you put this $item->data[8]; into a new array. Put just $array[] = $item->data[8]; and the you can use the answers. Commented Jun 3, 2016 at 9:52

5 Answers 5

1

Once you've got your array containing all your data, simple sum the array and then divide by the size of the array.. something along these lines

$average = (array_sum($array) / count($array));

Of course you may want to check for count($array) being 0;

Sign up to request clarification or add additional context in comments.

2 Comments

no good. because of: [$item->data[8]]; add element as array, not a value. array_sum will be 0.
Yes I'm just trying to impart the idea :)
0

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

Comments

0
if (count($array)>0){
    $avg = array_sum($array) / count($array);
}

1 Comment

no good. because of: [$item->data[8]]; add element as array, not a value.
0

I would personally do those calculations in the database before the data gets to your PHP script itself. See AVG().

If you can't for some reason use that I would output those values into a flat array and then just calculate the average. So something like :

function getAverage($data) {
  $flatArray = array();
  foreach ($data as $row) {
    if (!empty($row->8)) {
        $flatArray[] = $row->8;
    }
  }
  return (array_sum($flatArray)/count($flatArray));
}

EDIT: Moved to Object traversing on the data row, sorry, missed that initially and thought it was an array in all the nests.

Comments

0

Since you have a loop within your static Method; why not do the calculation therein and return it or add it to the JSON Data if You need your Data in JSON Format? Here's what's implied by the above:

        public static function getAverageSum($data) {
            $array      = [];
            $path       = $data->data[2];
            $sumTotal   = 0.00;     //<== YOU COULD JUST SUM IT DIRECTLY WITHOUT USING AN ARRAY
            foreach($path as $key => $item) {
                if ($key > 1) {
                    $array[]    = $item->data[8];
                    $sumTotal  += floatval($item->data[8]);
                }
            }

            // IF YOU ARE ONLY INTERESTED IN THE AVERAGE SUM YOU COULD EVEN ADD IT IT TO THE $array AS AN EXTRA KEY
            // LIKE SO:
            $arrLen             = count($array);
            $array['avgSum']    = $sumTotal/$arrLen;


            // IF YOU NEED YOUR DATA IN JSON... THEN RETURN THE JSON ENCODED DATA WITH SUM AS PART OF THE DATA.
            // YOU'D HAVE NO NEED FOR array_sum() SINCE YOU DID YOUR PREP-WORK ALREADY...
            return json_encode($array);

            // ALTERNATIVELY; IF ALL YOU NEED IS JUST THE AVERAGE SUM; YOU COULD AS WELL DIRECTLY RETURN $sumTotal/$arrLen
            return ($sumTotal/$arrLen);

        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.