使用数组循环遍历集合 - Laravel

我有一个集合,我使用雄辩的 findMany 方法从数据库中提取了这些集合。当我添加收藏时,它看起来像附加的图像。然后我尝试(在我的刀片中)遍历数组中的每个项目,以便我能够打印实际记录中的每个值。


$question = Question::whereIn('id', [23,25])->get();

然后在我的刀片中我正在尝试做:


@foreach ($question as $row => $innerArray)

    @foreach ($innerArray as $innerRow => $value)

        {{$value->question}} //I was expecting "What is your favourite food" here

        @foreach ($value->option as $choice)

            <li>{{$choice}}</li> //I was expecting the list of the options here

        @endforeach 

    @endforeach

@endforeach

http://img2.mukewang.com/643a6d450001289004370619.jpg

我究竟做错了什么?



PIPIONE
浏览 174回答 2
2回答

天涯尽头无女友

Eloquent 返回的所有多结果集都是该Illuminate\Database\Eloquent\Collection对象的实例,包括通过 get 方法检索或通过关系访问的结果。Eloquent 集合对象扩展了 Laravel基础集合,因此它自然继承了数十种用于流畅地处理底层 Eloquent 模型数组的方法。所有集合也用作迭代器,允许您像简单的 PHP 数组一样循环遍历它们:$questions = Question::whereIn('id', [23, 25, ..])->get();foreach ($questions as $question) {    echo $question->title; // What is your favourite food    echo $question->name; // food    foreach ($question->options as $option) {         echo $option; // Pizza    }}

慕尼黑的夜晚无繁华

正确的语法是这样的:@foreach ($question as $q)&nbsp; &nbsp; {{ $q->question }} //I was expecting "What is your favourite food" here&nbsp; &nbsp; &nbsp;@foreach ($q->options as $choice)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<li>{{$choice}}</li> //I was expecting the list of the options here&nbsp; &nbsp; &nbsp;@endforeach&nbsp;@endforeach
打开App,查看更多内容
随时随地看视频慕课网APP