首页 > 解决方案 > 如何正确地从数组中获取信息以便可以插入数据库?

问题描述

用户填写表格注册两个会议参与者并单击“注册”后,会出现一个包含请求数据的数组。

请求数据具有name存储在registration_type_id“1”(Jake)中注册的参与者的名称和在registration_type_id“4”(John)中注册的参与者的名称的数组。

数组也是surname如此,这个姓氏数组存储了每个注册类型的每个姓氏。

对于answer存储每个注册类型的每个答案的数组也是如此。

 "name" => array:2 [▼
        1 => array:1 [▼
          1 => "Jake"
        ]
        4 => array:1 [▼
          1 => "John"
        ]
      ]
      "surname" => array:2 [▼
        1 => array:1 [▼
          1 => "W"
        ]
        4 => array:1 [▼
          1 => "K"
        ]
      ]
      "answer" => array:1 [▼
        1 => array:1 [▼
          1 => array:6 [▼
            1 => "answer1"
            2 => "answer2"
          ]
        ]
      ]

疑问:我的疑问是如何从上面的数组结构中获取信息,以便将每个参与者存储在参与者表中,以及如何将每个答案存储在答案表中。

参与者表上方的数组内容应如下所示:

 id      registration_type_id                name             surname        registration_id
 1            1                            Jake                 W                 1 
 2            4                           John                 K                 1

答案表应如下所示:

 id       participant_id          question_id        answer
     1              1                  1              answer1
     1              1                  2              answer2

您知道如何正确实现这一目标吗?

我有下面的代码,首先在注册表中插入一个条目来存储注册:

# user object
$user = Auth::user();
# add registration to Database
$registration = Registration::create([
    'conference_id' => $id,
    'user_that_did_registration' => $user->id]
);

但是有必要将每个参与者存储在参与者表中,并将每个答案存储在答案表中。你知道如何正确地从上面的数组中获取必要的信息以存储在参与者表和答案表中,并使用下面的代码吗?

要在参与者表中插入,必须使用:

$participant_result = Participant::create([
      'name' => how to get the name of each participant from the array?,
      'surname' => how to get the surname of each participant from the array?,
      'registration_id' => $registration->id,
      'registration_type_id' => how to get the registration_type_id from the array?
  ]);

要在答案表中插入,必须使用:

 $answer = Answer::create([
        'question_id' => how to get each question id from the array?,
        'participant_id' => $participant_result->id,
        'answer' => how to  get each answer from the array?
    ]);

标签: php

解决方案


推荐阅读