Using a foreach variable in a Laravel view
我的MySQL表如下(相关部分):
1 2 3 | student_id (int) | engmins(int) | totalmins(int) | created_at (datetime) 1 | 50 | 100 | 2017-12-15 00:00:00 1 | 20 | 45 | 2017-12-15 00:00:00 |
我有以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | $students = StudentDetails::with('student','studentschool','classactivity') ->where('class', 1) ->orderBy('studentgrade', 'DESC') ->get(); $calculatePercentage = array(); foreach ($students as $s) { $fetchEngClassPercents= DB::table('ClassActivity') ->select(DB::raw('round((sum(engmins) * 60) / (sum(totalmins) * 60) * 100) as percents')) ->where('created_at', '>=', Carbon::now()->subDays(30)) ->where('student_id', '=', $s->student->id)->get(); foreach($fetchEngClassPercents as $f) { $calculatePercentage = $f->percents; var_dump($calculatePercentage); //Debug purposes } } var_dump($calculatePercentage); //Debug purposes $params = [ 'engClassPercentage' => $calculatePercentage, 'studentInfo' => $students, ]; return view('user.classes.engclass.index', $params); |
- 循环内的var_dump执行字符串(2)"43"NULL
- var_dump在循环外执行空值
这就是它在视图中的外观:
1 2 3 4 5 | <td> @foreach($engClassPercentage as $p) {{ $p->percents }} @endforeach </td> |
这在视图中不起作用,它只是不显示任何内容。
出于某种原因,$calculatePercentage在循环之外保持为空(在先前尝试转储var时)。当它在foreach循环中时,它执行查询。
奇怪的是,我声明了循环外部的数组($calculatePercentage)被分配给foreach循环中的变量。
老实说,我在这一点上迷路了,如果我能得到帮助,我会很高兴的。
将$CalculatePercentage=$F-Percents;更改为如下所示。然后在foreach部分将$p->percents更改为$p。
1 2 3 4 5 | $calculatePercentage[] = $f->percents; @foreach($engClassPercentage as $p) {{$p}} @endforeach |
$calculatePercentage将在每个循环上被覆盖,请将其更改为数组键
1 | $calculatePercentage[] = $f->percents; |
然后在foreach中调用$params数组
1 | @foreach($params['engClassPercentage'] as $p) |
您不存储在foreach循环中计算的值:
因此,这些值不会根据您的需求保持不变。
更新代码:
1 2 3 4 5 6 7 8 9 10 11 | foreach ($students as $s) { $fetchEngClassPercents= DB::table('ClassActivity') ->select(DB::raw('round((sum(engmins) * 60) / (sum(totalmins) * 60) * 100) as percents')) ->where('created_at', '>=', Carbon::now()->subDays(30)) ->where('student_id', '=', $s->student->id)->get(); foreach($fetchEngClassPercents as $f) { $calculatePercentage[] = $f->percents; // <-- This line is edited. } } |