【问题标题】:Perform average in array in Laravel在 Laravel 的数组中执行平均
【发布时间】:2019-01-11 05:19:06
【问题描述】:

我正在尝试计算表中的平均值。列名是term1_result,平均值在数组中,因为我的表中有很多学生和科目。我将它们按student_id 分组,但我总是得到一个零值。我正在使用Laravel 框架。

代码

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

结果

array:6 [▼
  0 => 0
  1 => 0
  2 => 0
  3 => 0
  4 => 0
  5 => 0
]

【问题讨论】:

标签: php laravel average


【解决方案1】:

你应该试试这个:

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

【讨论】:

    【解决方案2】:

    这是因为你的 SQL 内容!

    您是否已转储分数以查看结果?

    您必须对每个组中的每个项目求和。

    您可以查看this了解更多信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      相关资源
      最近更新 更多