在视图中以正确的格式显示数据

时间:2017-04-23 18:04:09

标签: laravel blade laravel-5.4 laravel-blade

用户可以填写表格,该表格基于多个问题,每个问题都有6个与之相关的字段。

表单信息存储在数据库中,如:

id / audit_id / question_id / score
1003    33          97      3
1004    33          97      0   
1005    33          97      2   
1006    33          97      0   
1007    33          97      2   
1008    33          97      0   
1009    33          98      3   
1010    33          98      1   
1011    33          98      3   
1012    33          98      1   
1013    33          98      3   
1014    33          98      0       

所以在上面的例子中,审计33有question_id 97和98,每个都有6个答案。

获取信息的控制器功能:

Audit::where('audit_id', $auditScore->id)
    ->with('rquestion')
    ->with('rquestion.auditQuestion')
    ->get();

返回数组中的每个问题:

Collection {#486 ▼
  #items: array:78 [▼
    0 => Audit {#490 ▶}
    1 => Audit {#491 ▶}
    2 => Audit {#492 ▶}
    3 => Audit {#493 ▶}
    4 => Audit {#494 ▶}
    5 => Audit {#495 ▶}
    6 => Audit {#496 ▶}
    7 => Audit {#497 ▶}
    8 => Audit {#498 ▶}
    9 => Audit {#499 ▶}

我面临的问题是我想循环访问数据,向用户显示以下内容:

  

一个问题及其6个答案,然后是下一个问题及其6个问题   答案

但是因为每个'问题行'都是单独返回的,所以我有一个问题和分数。因此,对于我展示的每一个分数,它都有问题!

每个问题总会有6个答案,所以我的想法是以某种方式用第一个分数打印问题,然后自己剩下的5个分数?

我不确定如何实现这一目标。如何获得question_id的所有6个分数?也许,每个question_id包含6个分数的数组?

非常感谢,

1 个答案:

答案 0 :(得分:0)

您只需按question_id对其进行分组即可 假设$auditList包含审核列表:

$groupedQuestions = [];
foreach ($auditList as $singleAudit)
{
    $groupedQuestions[$singleAudit->question_id][] = $singleAudit;
}

然后,你会有一个像这样的数组

array:2 [▼
  97 => array:3 [▼
    0 => Audit {#160 ▶}
    1 => Audit {#159 ▶}
    2 => Audit {#163 ▶}
  ]
  98 => array:1 [▼
    0 => Audit {#164 ▶}
    ...
  ]
  ...
]

如果需要,可以稍微更改代码并在“上部”数组中移动问题文本,这样就可以更容易地通过刀片获取

    foreach ($auditList as $singleAudit)
    {
        $groupedQuestions[$singleAudit->question_id]['question'] = $singleAudit->getQuestionText(); // assuming that you have a similar method on your entities
        $groupedQuestions[$singleAudit->question_id]['answers'][] = $singleAudit;
    }

您的结果数组与此类似

array:2 [▼
  97 => array:2 [▼
    "question" => "This is the question text"
    "answers" => array:3 [▼
      0 => Audit {#160 ▶}
      1 => Audit {#159 ▶}
      2 => Audit {#163 ▶}
    ]
  ]
  98 => array:2 [▼
    "question" => "This is the question text"
    "answers" => array:1 [▼
      0 => Audit {#164 ▶}
    ]
  ]
]

并通过刀片获取将是这样的

@foreach($questions as $question)
The question is: {{$question['question']}}    <br />
Answers are: <br />
    @foreach($question['answers'] as $answer)
        {{$answer->id}} <br />
    @endforeach
@endforeach

印刷

  

问题是:这是问题文本
  答案是:
  1033
  1034
  1035
  ...
  问题是:这是问题文本
  答案是:
  1035
  ......