多维数组php post
我创建了一个表单,用于向某个位置输入计划,该位置将有多个计划多维数组php post,php,html,mysql,laravel,Php,Html,Mysql,Laravel,我创建了一个表单,用于向某个位置输入计划,该位置将有多个计划 表单如下所示(我可以根据需要添加更多的输入表单) 时间表表格 +----+----------+----------+ | id | location | address | +----+----------+----------+ | 1 | loc 1 | addr 1 | | 2 | loc 2 | addr 2 | +----+----------+----------+ +----+------
表单如下所示(我可以根据需要添加更多的输入表单)
时间表
表格
+----+----------+----------+
| id | location | address |
+----+----------+----------+
| 1 | loc 1 | addr 1 |
| 2 | loc 2 | addr 2 |
+----+----------+----------+
+----+----------+----------+-------+------------+
| id | day | start | end | address_id |
+----+----------+----------+-------+------------+
| 1 | day a | start a | end a | 1 |
| 2 | day b | start b | end b | 1 |
| 3 | day c | start c | end c | 2 |
| 4 | day d | start d | end d | 2 |
+----+----------+----------+-------+------------+
我已经读到我需要使用foreach
来实现这一点,但问题是如何循环输入并确保计划具有正确的address\u id
值
我使用拉威尔:
$address = Input::get('address');
$location = Input::get('location');
$day = Input::get('day');
$start = Input::get('start');
$end = Input::get('end');
foreach($location as $key => $value) {
$addr = new Address;
$addr->location = $location[$key];
$addr->address = $address[$key];
$addr->save();
foreach($day as $key => $value) {
$sched = new Schedule;
$sched->day = $day[$key];
$sched->start = $start[$key];
$sched->end = $end[$key];
$sched->address_id = $addr->id;
$sched->save();
}
}
例如,您需要按
地址
循环,并首先在地址
表中插入。之后,您需要获取插入行的id,并在明细表中插入时使用它
由于您没有尝试任何代码,我只在这里解释您应该如何做,如果某些代码不起作用,请让我知道您尝试了什么,以及出现了什么错误
foreach($_POST['address'] as $key => $value){
//insert to address table: $_POST['location'][$key] and $_POST['address'][$key]
//$last_inserted_id_from_address = Get the latest inserted id from address table.
//insert to schedules tables: $_POST['day'][$key] ,.... and $last_inserted_id_from_address
}
更新
如果希望1对1进行匹配,则不需要循环两次。
将循环更改为:
foreach($location as $key => $value) {
$addr = new Address;
$addr->location = $location[$key];
$addr->address = $address[$key];
$addr->save();
//Use the same $key when creating Schedule. For each address will create one schedule.
$sched = new Schedule;
$sched->day = $day[$key];
$sched->start = $start[$key];
$sched->end = $end[$key];
$sched->address_id = $addr->id;
$sched->save();
}
那么您使用的是哪种PHP MYSQL APImysqli.*
或PDO
?查看您迄今为止的尝试也会很有用!我已经尝试过,从您的代码中,天
,开始
,结束
值将重复2次,地址id
1和2都将具有天a
,天b
,天c
,和天d
值,而我想让第a天
和第b天
只连接到地址\u id
1<代码>第c天
和第d天
仅连接到地址\u id
2
foreach($location as $key => $value) {
$addr = new Address;
$addr->location = $location[$key];
$addr->address = $address[$key];
$addr->save();
//Use the same $key when creating Schedule. For each address will create one schedule.
$sched = new Schedule;
$sched->day = $day[$key];
$sched->start = $start[$key];
$sched->end = $end[$key];
$sched->address_id = $addr->id;
$sched->save();
}