我目前正在做一个项目。我有一个复选框(用户将选择公司提供的服务类型)。当我尝试在我的控制器中发布所选的服务(例如,检查了2个服务)时,我只获得一项服务。问题是如何在复选框中获取多个值?
注意:我也尝试在我的控制器中使用foreach,我收到一些错误,例如“为foreach()提供的无效参数”。
查看
<label>Desired Service</label> <br>
<?php foreach($services as $s):?>
<label><input type="checkbox" name="service_name[]" value="<?= $s->service_name?>"><?= $s->service_name?></label>
<br>
<?php endforeach?>
控制器
$this->form_validation->set_error_delimiters('<div class="alert alert-danger" role="alert">', '</div>');
$this->form_validation->set_rules('full_name', 'Fullname', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('contact', 'Contact', 'required');
$this->form_validation->set_rules('date', 'Date', 'required');
$this->form_validation->set_rules('address', 'Address', 'required');
$this->form_validation->set_rules('zip_code', 'Zip Code', 'numeric|required');
$this->form_validation->set_rules('province', 'Province', 'required');
$this->form_validation->set_rules('date', 'Date', 'required');
$this->form_validation->set_rules('service_name', 'Service', 'required');
if ($this->form_validation->run() == FALSE) {
$this->index();
}
else {
$service_name = implode(', ', $_POST['service_name']);
$event = array(
'full_name' => $this->input->post('full_name'),
'email' => $this->input->post('email'),
'contact' => $this->input->post('contact'),
'address' => $this->input->post('address'),
'zip_code' => $this->input->post('zip_code'),
'state_province' => $this->input->post('province'),
'date' => $this->input->post('date'),
'service' => $service_name
);
$this->EventModel->add_event($event);
echo "<script>
window.alert('Your Desired Date is being Proccessed!');
location.href = '".site_url('/')."';
</script>";
}
答案 0 :(得分:3)
从
改变$service_name = $_POST['service_name'];
foreach($service_name as $key =>$value)
{
echo $value;
}
die;
到
$service_name = implode(',',$_POST['service_name']);
echo $service_name;
答案 1 :(得分:3)
我希望它能解决你的问题
if (!empty($this->input->post('service_name'))) {
foreach ($this->input->post('service_name') as $key => $val) {
$data[] = array(
'service_name' => $_POST['service_name'][$key]
);
}
foreach ($data as $item) {
echo $item['service_name'];
}
答案 2 :(得分:1)
尝试:
$service_name = $this->input->post('service_name');
for($i=0;$i < count($service_name);$i++){
echo $service_name[$i];
}