我不确定问题标题是否正确,但我想要做的在下面的示例中很清楚 我有 3 个数组,我想将数据存储在一张表中
表结构是这样的
表名:tour_transsports
身份证
transport_id
transport_track
transport_note
来自刀片的数组
"transport_id" => array:2 [
1 => "1"
5 => "5"
]
"transport_track" => array:3 [
1 => " from airport to the hotel"
3 => null
5 => " be ready at 4:pm"
]
"transport_note" => array:3 [
1 => "from hotel to the beach"
3 => null
5 => " bring ur swiming suite"
]
如你所见,id 是 1 和 5,所以我想在这里存储两行
id = 1,transport_id = 1,transport_track = 从机场到酒店,transport_note = 4:pm 准备好
id = 2,transport_id = 5,transport_track = 从酒店到海滩,transport_note = 带上你的游泳套件
我试图这样做,但无法正确
if(!empty($request->transport_id))
{
foreach ($request->transport_id as $key => $transport_id) {
foreach ($request->transport_track as $key => $track) {
foreach ($request->transport_note as $key => $transport_note) {
TourTransport::create([
'transport_id' =>$transport_id,
'transport_track' =>$track[$transport_id],
'transport_note' =>$transport_note[$transport_id]
]);
}
}
}
}
答案 0 :(得分:0)
您可以使用此代码来实现您的结果:
$data = $request->only('transport_id', 'transport_track', 'transport_note');
foreach ($data['transport_id'] as $key => $transportId) {
TourTransport::create([
'transport_id' => $transportId,
'transport_track' => $data['transport_track'][$key],
'transport_note' => $data['transport_note'][$key],
]);
}
现在 $results 包含所需的数据。然而,更好的解决方案可能是配置您的 html 表单以在单个数组条目中发送相关数据,例如:
<input type="text" name="transports[0][transport_id]">
<input type="text" name="transports[0][transport_track]">
<input type="text" name="transports[0][transport_note]">
<input type="text" name="transports[1][transport_id]">
<input type="text" name="transports[1][transport_track]">
<input type="text" name="transports[1][transport_note]">
您还可以使用 Javascript/php 循环来生成表单输入。然后您将在服务器端以格式良好的结构接收表单数据,例如:
"transports" => array:2 [
[
'transport_id' => 1,
'transport_track' => 'from airport to the hotel',
'transport_note' => 'be ready at 4:pm',
],
[
'transport_id' => 5,
'transport_track' => 'from hotel to the beach',
'transport_note' => ' bring ur swiming suite',
],
]