将数组从控制器传递到视图 - Laravel

时间:2018-01-01 14:31:43

标签: php arrays laravel multidimensional-array

我正在尝试制作测验应用程序。我有各种类别的600多个问题,如jp,sn,ei等。现在我想随机向各类用户展示问题和选项。但是得到错误。有人会帮助我做对吗我尝试过这样的事情 - 在我的Controller.php中

public function index()
{
    $jp = DB::table('e_questions')->take(2)->inRandomOrder()->where('dichotomy', '=', 'JP')->get();
    $sn = DB::table('e_questions')->take(2)->inRandomOrder()->where('dichotomy', '=', 'SN')->get();
    $ei = DB::table('e_questions')->take(2)->inRandomOrder()->where('dichotomy', '=', 'EI')->get();
    $tf = DB::table('e_questions')->take(2)->inRandomOrder()->where('dichotomy', '=', 'TF')->get();
    $equestions = array("$jp","$sn","$ei","$tf");
    //dd($equestions);

  return view('question.english.index', compact('equestions'));
}

在我看来index.blade.php

             @foreach($equestions as $equestion)
                 <p>{{ $equestion->question }}</p>
                 <p>{{ $equestion->option1 }}</p>
                 <p>{{ $equestion->option2 }}</p>
             @endforeach

1 个答案:

答案 0 :(得分:1)

首先,创建一个这样的数组:

$equestions = [$jp, $sn, $ei, $tf];

然后迭代数据:

@foreach($equestions as $equestionType)
    @foreach($equestionType as $equestion)
        <p>{{ $equestion->question }}</p>
        <p>{{ $equestion->option1 }}</p>
        <p>{{ $equestion->option2 }}</p>
    @endforeach
@endforeach