在Laravel视图中使用foreach变量

时间:2017-12-16 11:12:25

标签: php laravel foreach blade laravel-blade

我的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);
  • var_dump INSIDE循环执行 string(2)“43”NULL
  • var_dump OUTSIDE循环执行 NULL

这就是它在视图中的样子:

<td>
    @foreach($engClassPercentage as $p)
        {{ $p->percents }}
    @endforeach
</td>

这在视图中不起作用,它根本不显示任何内容。

由于某种原因,$ calculatePercentage在循环之外保持为null(在之前尝试转储var时)。当它在foreach循环中时,它会执行查询。

奇怪的是,我声明循环外的数组($ calculatePercentage)在foreach循环中赋值变量。

说实话,我很遗憾,如果能得到帮助,我会很高兴。

3 个答案:

答案 0 :(得分:2)

$ calculatePercentage在每个循环中被覆盖,将其更改为数组键

$calculatePercentage[] = $f->percents;

然后在你的foreach中调用$ params数组

@foreach($params['engClassPercentage'] as $p)

答案 1 :(得分:2)

更改$ calculatePercentage = $ f-percentnts;喜欢下面。 然后在foreach部分将$ p-&gt;百分比更改为$ p。

$calculatePercentage[] = $f->percents;

@foreach($engClassPercentage as $p)
   {{$p}}
@endforeach

答案 2 :(得分:0)

您没有存储在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.
    }
}