我有一个表,其中包含以下字段ID,名称,类型和颜色
我有以下输入字段,想添加多行
<input type="text" name="com_name[]" value="a">
<input type="text" name="com_type[]" value="1">
<input type="text" name="com_color[]" value="red">
<input type="text" name="com_type[]" value="2">
<input type="text" name="com_color[]" value="green">
<input type="text" name="com_name[]" value="b">
<input type="text" name="com_type[]" value="1">
<input type="text" name="com_color[]" value="black">
<input type="text" name="com_type[]" value="2">
<input type="text" name="com_color[]" value="yellow">
我正在尝试laravel,但是如果有人可以展示如何在核心PHP中做到这一点,那将是很大的帮助
$com_name = array();
$com_name = Input::get('com_name');
$dataSet = [];
foreach ($com_name as $name) {
$dataSet[] = [
'name' => $request->com_name,
'type' => $request->com_type,
'color' => $request->com_color,
];
}
DB::table('extra')->insert($dataSet);
我希望在mysql表中显示以下输出
ID Name Type Color
1 a 1 red
2 a 2 green
3 b 1 black
4 b 2 yellow
答案 0 :(得分:0)
我建议使用这样的显式顶级索引在HTML中创建子数组...
<input type="text" name="com_name[0]" value="a">
<input type="text" name="com_type[0][]" value="1">
<input type="text" name="com_color[0][]" value="red">
<input type="text" name="com_type[0][]" value="2">
<input type="text" name="com_color[0][]" value="green">
<input type="text" name="com_name[1]" value="b">
<input type="text" name="com_type[1][]" value="1">
<input type="text" name="com_color[1][]" value="black">
<input type="text" name="com_type[1][]" value="2">
<input type="text" name="com_color[1][]" value="yellow">
然后在您的PHP中,您将使用第二个foreach循环遍历这些子数组...
foreach ($com_name as $index => $value) {
$type = $request->com_type[$index];
foreach($type as $subIndex => $typeVal)
{
$dataSet[] = [
'name' => $value,
'type' => $typeVal,
'color' => $request->com_color[$index][$subIndex],
];
}
}
我个人不使用Laravel,因此假设您上面具有的特定于Laravel的代码是正确的。