PHP将多个表单字段处理为复选框字段


PHP process multiple form fields to checkbox field

我试图将数据处理到API引用'custom11746175'的字段。但是,这个字段有复选框,我想在必要时处理多个值。现在,我只有这个,它只会处理中的一个值"Off-g","On-g","On-h"或"On-i"(最后定义的一个):

if (($_POST['custom13346240'] == 'Off-g')) {
$contactData['custom11746175'] = "Off-g";
}
if (($_POST['custom13346240'] != 'Off-g')) {
$contactData['custom11746175'] = "On-g";
}
if ($_POST['custom13500281']) {
$contactData['custom11746175'] = "On-h";
}           
if ($_POST['custom11746175'] == 'Yes') {
$contactData['custom11746175'] = "On-i";
}

如果我想处理所有的定义值(数字可以变化)并在复选框中标记它们,我需要改变什么?我是否应该构造一个数组,以获得多维域之类的东西?

数组就是你需要的,如果你在$contactData['custom11746175']变量后面加上双括号[]它会像这样将新项目添加到$contactData['custom11746175']的数组中…

if (($_POST['custom13346240'] == 'Off-g')) {
    $contactData['custom11746175'][] = "Off-g";
}
if (($_POST['custom13346240'] != 'Off-g')) {
    $contactData['custom11746175'][] = "On-g";
}
if ($_POST['custom13500281']) {
    $contactData['custom11746175'][] = "On-h";
}           
if ($_POST['custom11746175'] == 'Yes') {
    $contactData['custom11746175'][] = "On-i";
}

要获取数组中的第一个元素你只需输入$contactData['custom11746175'][0]

来自Solve360的团队指出,这些字段允许多个复选框使用逗号分隔值。因此,我将上面的代码更改为:

$items = "";
if (($_POST['custom13346240'] == 'Off-g')) {
    $items = $items . ',' . "Off-g";
}
if (($_POST['custom13346240'] != 'Off-g')) {
    $items = $items . ',' . "On-g";
}
if ($_POST['custom13500281']) {
    $items = $items . ',' . "On-h";
}            
if ($_POST['custom11746175'] == 'Yes') {
    $items = $items . ',' . "On-i";
}
$contactData['custom11746175'] = $items;

希望能帮到别人。