我通过POST从表单中获取了大量数据。例如,以下是一些数据:
EVENT_DATE:
Array (
[0] => 2017-04-02
[1] => 2017-04-02
[2] => 2017-04-03 )
equipment_name:
Array
(
[0] => Array
(
[0] => Mic
[1] => Sound System
[2] => Wireless Mic
[3] => Two Point Stage Wash
)
[1] => Array
(
[0] => Sound System
)
[2] => Array
(
[0] => Projection Package
[1] => Gobo
[2] => Audio Engineer
)
)
为了保存这些数据,我正在做两个foreach循环:
foreach ($_POST['event_date'] as $key => $date) {
echo "event number [".$key."]<br>";
//insert into table value $_POST['event_date'][$key]
foreach ($_POST['equipment_name'] as $ekey => $value) {
echo "equipment number [".$key."][".$ekey."]<br>";
//insert into table value $_POST['equipment_name'][$key][$ekey];
}
}
不幸的是我的结果如下:
event number [0]
equipment number [0][0]
equipment number [0][1]
equipment number [0][2]
event number [1]
equipment number [1][0]
equipment number [1][1]
equipment number [1][2]
event number [2]
equipment number [2][0]
equipment number [2][1]
equipment number [2][2]
您可以注意到,嵌套密钥($ ekey)等于第一个密钥,不显示超过该数字的项目(例如:设备编号[0] [3]),如果设备数量低于设备数量则不保存任何内容该编号(例如:设备编号[1] [1]和[1] [2])。
为什么嵌套循环有这种行为?我怎么能解决这个问题?
答案 0 :(得分:2)
如果我理解你的问题,我认为你想从$_POST['equipment_name']
访问一个特定的嵌套数组,但你总是访问外部数组。这是一个简单的修复,将您的第二个foreach更改为:
foreach ($_POST['equipment_name'][$key] as $ekey => $value) {
^^^^^^