参与者数组具有以下结构:
array:1 [▼
"participant" => array:2 [▼
1 => array:5 [▼
"name" => "John"
"surname" => "W"
"answer" => array:6 [▼
0 => "text answer"
1 => "long answer"
2 => "check1"
3 => "rb1"
4 => "selectmenu1"
5 => "img.jpg"
]
"question_id" => array:6 [▼
0 => "1"
1 => "2"
2 => "3"
3 => "4"
4 => "5"
5 => "6"
]
"rtypes" => "1"
]
2 => array:3 [▼
"name" => "Jake"
"surname" => "K"
"rtypes" => "4"
]
]
]
数组的每个索引都包含有关正在会议中注册的参与者的数据。在这种情况下,数组索引“ 1”中的参与者具有名称“ John”和姓“ w”,并且正在以id“ 1”的注册类型进行注册。此注册类型具有6个与之相关的自定义问题,因此,以注册形式针对正在对此自定义问题进行注册答案的用户,并将答案存储在“答案”数组中。
数组索引“ 2”中的参与者没有答案,因为他正在使用ID为4的注册类型进行注册,此ID为4的注册类型没有任何自定义问题,因此在注册表中仅从该参与者那里收集了姓名和姓氏,没有答案。
疑问:如何将每个参与者的答案存储在答案表中
现在,我想将每个参与者的信息存储在参与者表中,并将每个参与者的答案存储在答案表中。存储在参与者表中的代码可以正常工作。
但是,由于答案和question_id是数组,因此无法存储每个答案。您知道如何正确地将每个答案和Question_id存储在答案表中吗?
foreach ($participants['participant'] as $k => $participant) {
$name = $participant['name'];
$surname = $participant['surname'];
$participant_result = Participant::create([
'name' => $name,
'surname' => $surname,
'registration_id' => $registration->id,
'registration_type_id' => $participant['rtypes']
]);
//var_dump($participant['question_id']);
// the error is here
// store each answer of each participant that has answers
if (isset($participant['question_id'])) {
$answer = Answer::create([
'question_id' => $participant['question_id'],
'participant_id' => $participant_result->id,
'answer' => $participant['answer'],
]);
}
}
答案 0 :(得分:1)
我认为您需要为每个答案创建一个答案。我只在代码中添加了一个循环和一些数组索引。
if (isset($participant['question_id'])) {
for ($i=0; $i < count($participant["question_id"]); $i++) {
$answer = Answer::create([
'question_id' => $participant['question_id'][$i],
'participant_id' => $participant_result->id,
'answer' => $participant['answer'][$i]
]);
}
}