首页 > 解决方案 > 通过 foreach 循环遍历数组以显示一些数据,并使用相同的数组显示单个输出

问题描述

我从一个有 5 行的查询中向刀片发送以下输出。每行有一个问题和一个答案,其中5行中的问题相同,而每行的答案不同。我只想显示一次问题,并在其下方显示 5 个答案。我正在发送一个数组,如下所示:

array:2 [▼
  0 => {#338 ▼
    +"id": 25
    +"created_at": "2019-10-18 11:13:17"
    +"updated_at": "2019-10-18 11:13:17"
    +"title": "question"
    +"body": """
       \r\n
         aasasas
      """
    +"ttype": 0
    +"cat": 0
    +"a_id": 25
    +"tag": ""
    +"appr": 0
    +"user_id": 6
    +"comment_id": 0
    +"parent_id": null
    +"ppoints": null
    +"status": 0
    +"arank": 1
    +"qatype": 1
    +"country": "Egypt"
    +"wwide": 0
  }

以下显示了该问题的一次问题和不止一次的答案。当然,这段代码给出了Trying to get property of non-object错误,因为它也期待这个问题的 foreach。

@if(!empty($updt_11))

<p class="collapsible"> {{$updt_11->title}} </p> // this is the question

@foreach($updt_11 as $updt_11_a)   
<div class= "content">
<p>{{$updt_11_a->body}} </p>   //This is the answer
</div>
@endforeach
@endif

如何使用同一个数组提出一次问题和多次回答?

标签: phplaravel

解决方案


首先,如果您可以从后端更改数组并在子数组传递答案中添加一次问题,这对您来说很容易。

如果您想使用已通过的相同数组,请执行

Point 1. 用于index显示0问题

Point 2. 正如你已经使用过的,用于foreach显示答案

@if(!empty($updt_11))

<p class="collapsible"> {{$updt_11[0]->title}} </p> // this is the question

@foreach($updt_11 as $updt_11_a)   
<div class= "content">
<p>{{$updt_11_a->body}} </p>   //This is the answer
</div>
@endforeach
@endif

推荐阅读