在Laravel视图中使用foreach变量
我的MySQL表看起来像这样(相关部分):
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
我有以下代码:
$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);
这是它在视图中的外观:
<td>
@foreach($engClassPercentage as $p)
{{ $p->percents }}
@endforeach
</td>
这在视图中不起作用,它只是不显示任何内容。
出于某种原因,$ calculatePercentage在循环之外保持为空(在先前尝试转储var时)。 当它在foreach循环中时,它执行查询。
奇怪的是我声明在循环外面的数组($ calculatePercentage)在foreach循环中被赋予了变量。
说实话,我很失落,如果能得到帮助,我会很高兴。
更改$ calculatePercentage = $ f-percents; 喜欢下面。 然后在foreach部分将$ p-> percent改为$ p。
$calculatePercentage[] = $f->percents;
@foreach($engClassPercentage as $p)
{{$p}}
@endforeach
$ calculatePercentage在每个循环中被覆盖,将其更改为数组键
$calculatePercentage[] = $f->percents;
然后在你的foreach中调用$ params数组
@foreach($params['engClassPercentage'] as $p)
您不存储在foreach循环中计算得到的值:
因此,这些价值观不会按照您的要求持续存在。
更新的代码:
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.
}
}
链接地址: http://www.djcxy.com/p/1529.html