为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
PIPIONE 2023-04-15 17:23:53
我有一个集合,我使用雄辩的 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我究竟做错了什么?
查看完整描述

2 回答

?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

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

    }

}


查看完整回答
反对 回复 2023-04-15
?
慕尼黑的夜晚无繁华

TA贡献1864条经验 获得超6个赞

正确的语法是这样的:


@foreach ($question as $q)

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

     @foreach ($q->options as $choice)

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

     @endforeach 

@endforeach


查看完整回答
反对 回复 2023-04-15
  • 2 回答
  • 0 关注
  • 132 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信