php - 通过 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
如何使用同一个数组提出一次问题和多次回答?
解决方案
首先,如果您可以从后端更改数组并在子数组传递答案中添加一次问题,这对您来说很容易。
如果您想使用已通过的相同数组,请执行
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
推荐阅读
- python - 如何在引用其他行上的数据时对 DF 中的每一行执行计算?
- node.js - Jest 如何测试 Express API POST 请求?
- laravel - Laravel 数据库迁移列更改为 Unique 和 Nullable 导致错误
- azure - 将 NSG 应用于子网时,不需要 Azure ARM 模板“copyIndex”
- apache - .htaccess 规则 FilesMatch 到所有子文件夹(子文件夹是随机创建的)
- c# - 尝试与 Lex 交互时出现 424 错误
- sql - 如何根据一列排序,然后再次使用另一列排序输出?
- processing - 正在处理的纸牌游戏套装
- python - 为什么我对 OVH 的 API 调用在我分配的 ipBlock 上不起作用?
- kubernetes - Kubernetes liveness/readiness 问题和 json 返回