php 如何在提交表单时使用 isset 输入为数组分配多个值

How to assign array multiple values with isset input on form submition in php

我正在尝试在 isset() 之后获取数组中提交的表单值,但它仅在数组中存储最后一个 isset() 值。获取数组中所有非空值以传递给插入函数的正确方法是什么。

$table = 'booking';
if(isset($_POST['tourID'])){
    $data = array('tour_fk' => $this->input->post('tourID'));
}
if(isset($_POST['bookingNumber'])){
    $data = array('booking_number' => $this->input->post('bookingNumber'));
}
$query = $this->dashboard_model->insert($table, $data);

正确的方法是向 $data 添加新密钥而不是重新分配它:

if (isset($_POST['tourID'])){
    $data['tour_fk'] = $this->input->post('tourID');
}
if (isset($_POST['bookingNumber'])){
    $data['booking_number'] = $this->input->post('bookingNumber');
}

您可以像 this.Make 那样实现所有非空键的数组 values.Not 需要为每个发布的 items.Just 编写 isset() 使用 foreach loop.And 实现你的结果。

$table = 'booking';
foreach($_POST as $key=>$value) {
    if(isset($_POST[$key])) {
        $data[$key]=$this->input->post($key);
    }
}
//print_r($data);

这里给你举个例子..

$array = array('tour_fk'=>1,'booking_number'=>11,'empty_field'=>NULL);
foreach($array as $key=>$value) {
    if(isset($array[$key])) {
        $data[$key]=$value;
    }
}
    print_r($data);

输出:

Array ( [tour_fk] => 1 [booking_number] => 11 )//without null values