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

问题描述 投票:2回答:1

我正在尝试制作测验应用程序。我有各种类别的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
php arrays laravel multidimensional-array
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.