【问题标题】:Access JSON array within Laravel foreach loop在 Laravel foreach 循环中访问 JSON 数组
【发布时间】:2017-08-20 13:15:32
【问题描述】:

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

功能:

$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参数?

非常感谢。

【问题讨论】:

    标签: php json laravel foreach laravel-5.4


    【解决方案1】:
    <p>{{$answer->question->audit_question->question}}</p>
    

    获取问题编号

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

    希望对你有帮助

    【讨论】:

    • 我怎么能看到$answer 的18 个结果真的很奇怪,当我只输出{{ $answer-&gt;question }} 时它返回1 - 18 的整数。然而当我尝试访问question 关系时,我得到Trying to get property of non-object。这是为什么呢?
    • 可能不是所有的审计都有问题。所以你可以做一个 if 语句来检查问题是否包含某些东西,然后再尝试访问它的属性/属性
    【解决方案2】:

    这样做:

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

    【讨论】:

      【解决方案3】:

      如果$answer真的是一个JSON(string),那么你必须先解码:

      @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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-29
        • 2013-08-19
        • 2012-07-09
        • 1970-01-01
        相关资源
        最近更新 更多