访问Laravel foreach循环中的JSON数组

时间:2017-03-27 17:39:31

标签: php json laravel foreach laravel-5.4

我有一个函数可以返回我需要在视图中操作的数据。数据基于关系从各种表链接:

功能:

$auditResults = Audit::where('audit_id', $id)
   ->with('question', 'question.auditQuestion')
   ->get();

查看:

@foreach($auditResults as $answer)
    <p>{{$answer}}</p>
@endforeach

$ answer的输出:

{  
   "id":1,
   "audit_id":1,
   "audit_questions_details_id":2,
   "question":{  
      "id":2,
      "audit_question_id":2,
      "question_number":1,
      "comment":1,
      "header":0,
      "created_at":"2017-03-27 12:16:50",
      "updated_at":"2017-03-27 12:16:50",
      "audit_question":{  
         "id":2,
         "audit_detail_id":1,
         "question":"THIS IS WHAT I WOULD LIKE TO OUTPUT",
         "created_at":"2017-03-27 12:16:50",
         "updated_at":"2017-03-27 12:16:50"
      }
   },
   "score":null,
   "comment":null,
   "created_at":null,
   "updated_at":null
}

foreach循环中,如何输出每个结果的question参数?

非常感谢。

3 个答案:

答案 0 :(得分:0)

这样做:

{{ $answer->question->comment }}

答案 1 :(得分:0)

<p>{{$answer->question->audit_question->question}}</p>

获取问题编号

<p>{{$answer->question->question_number}}</p>

希望有所帮助

答案 2 :(得分:0)

如果$answer真的是JSON (字符串),那么您必须先解码它:

@foreach($auditResults as $answer)
    <?php $answer = json_decode($answer) ?>
    <!-- Now you have access to an PHP StdObject with your data -->
    <p>{{$answer->question}}</p>
@endforeach