我的表格看起来像这样
+---------+-------------+----------+
| day | start_time | end_time |
+---------+-------------+----------+
| monday | 10:00:00 | 12:00:00 |
+---------+-------------+----------+
我从表单获得的关联数组看起来像这样
[timeslot] => Array
(
[1] => Array
(
[weekday] => 1
[from] => Array
(
[0] => 1:15 PM
[1] => 4:15 PM
)
[to] => Array
(
[0] => 2:15 PM
[1] => 5:15 PM
)
)
[2] => Array
(
[weekday] => 2
[from] => Array
(
[0] =>
)
[to] => Array
(
[0] =>
)
)
[3] => Array
(
[weekday] => 3
[from] => Array
(
[0] =>
)
[to] => Array
(
[0] =>
)
)
[4] => Array
(
[weekday] => 4
[from] => Array
(
[0] =>
)
[to] => Array
(
[0] =>
)
)
[5] => Array
(
[weekday] => 5
[from] => Array
(
[0] =>
)
[to] => Array
(
[0] =>
)
)
[6] => Array
(
[weekday] => 6
[from] => Array
(
[0] =>
)
[to] => Array
(
[0] =>
)
)
[7] => Array
(
[weekday] => 7
[from] => Array
(
[0] => 1:15 PM
)
[to] => Array
(
[0] => 3:15 PM
)
)
)
Codeigniter中的正常数组插入并不适用于此。任何解决此问题的工作。
我需要存储这个
+---------+-------------+----------+
| day | start_time | end_time |
+---------+-------------+----------+
| monday | 12:30:00 | 01:30:00 |
| monday | 04:30:00 | 06:30:00 |
+---------+-------------+----------+
我尝试使用
插入它$this->db->insert('time_slots', $data);
但这是我所拥有的关联格式的失败。
如果from和to是数组
,我还想过循环遍历我的数组并使用上述命令插入数据,但我怀疑性能问题。
答案 0 :(得分:1)
像这样制作数组并传递给模型
$weekDay = array('1'=>'Sunday','2'=>'Monday','3'=>'Tuesday','4'=>'Wednesday','5'=>'Thurday','6'=>'Friday','7'=>'Saturday');
foreach($_POST['timeslot'] as $key=>$val){
foreach($val['from'] as $k=>$v){
$day = $val['weekday'];
$data[] = array(
'day'=>$weekDay[$day],
'start_time'=>$v['from'],
'end_time'=>$val['to'][$k]
);
}
}
$this->db->insert_batch('time_slots', $data);
答案 1 :(得分:0)
让它像这样工作
foreach ($_POST['timeslot'] as $key => $val) {
switch($val['weekday']){
case 1:
$val['day']='monday';
break;
case 2:
$val['day']='tuesday';
break;
case 3:
$val['day']='wednesday';
break;
case 4:
$val['day']='thursday';
break;
case 5:
$val['day']='friday';
break;
case 6:
$val['day']='saturday';
break;
case 7:
$val['day']='sunday';
break;
}
if(count(array_filter($val['from']))>0){
foreach($val['from'] as $k=>$v){
$tmp= array(
'day'=>$val['day'],
'start_time'=>$v,
'end_time'=>$val['to'][$k]
);
array_push($slots,$tmp);
}
}
}
依靠$val['from']
这样count(array_filter($val['from']))
删除空数组和空数组。