1

I'm trying to calculate an average in my table. The column name is term1_result and the average is in the array since my table has many students and subjects. I group them by student_id, but I always end up getting a zero value. I'm using the Laravel framework.

Code

$scores = Grades::with('student', 'subject')->groupBy('student_id')->get();

foreach($scores as $score) {
    foreach($score as $key => $value) {
        $sum_arr[] = $value['term1_result'];
    }
    $avg = array_sum($sum_arr) / count($sum_arr);
    $avgarr[] = $avg;
}

dd($avgarr);

Result

array:6 [▼
  0 => 0
  1 => 0
  2 => 0
  3 => 0
  4 => 0
  5 => 0
]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Noob
  • 27
  • 7

2 Answers2

0

This is because of your SQL content!

Have you dump your scores to see result?

You must sum over each items in each groups.

You can see this to learn more

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hamed Zarei
  • 21
  • 1
  • 5
0

You should try this:

$scores = Grades::with('student','subject')->groupBy('student_id')->avg('term1_result');