2017-04-23 87 views
1

用戶可以填寫表單,該表單基於多個問題,每個問題有6個與其關聯的字段。在視圖中以正確的格式顯示數據

形式信息被存儲在DB喜歡:

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

你可以簡單地將它們分組由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 

打印

的問題是:這是問題文本
答案是:
...
的問題是:這是問題文本
答案是:
...

+1

一個巨大的幫助!並進行了徹底的解釋。我設法通過使用與模型相關的關係來獲取問題名稱。謝謝LombaX! – Ben

相關問題