创建变量Array name来存储$_POST数组


Create variable Array name to store a $_POST array

我正在处理一个有很多复选框的表单。当检查是否填充了所有必填字段产生错误时,我的表单再次显示给定的预填充数据(文本和复选框)。我的复选框可以分配给4个不同的主题,所以我为每个主题填充一个数组。

所以基本上我为每个Topic取$_POST数据并从中创建一个数组。如果没有一个主题的复选框被填充,我必须创建一个空数组,因为我需要一个数组,以便使我的复选框得到预检(我使用in_array来检查checkboxvalue是否设置)。

我对php很陌生,所以我试着为这个目的做一个函数(常规的方式工作得很好)。

我的函数:

function fill_checkboxarray($topic)
{
    if(!empty($_POST["".$topic.""]))
    {
        ${$topic} = $_POST["".$topic.""];
    }
    else
    {
        ${$topic} = array();
    }
    return ${$topic};
}

在我的脚本中,我将主题的名称设置为传递给函数的变量:

$topic = "saunterstuetzt";
fill_checkboxarray($topic);
$topic = "sageplant";
fill_checkboxarray($topic);
$topic = "osunterstuetzt";
fill_checkboxarray($topic);
$topic = "osgeplant";
fill_checkboxarray($topic);

我得到以下$_POST数组:

$_POST["saunterstuetzt"]
$_POST["sageplant"]
$_POST["osunterstuetzt"]
$_POST["osgeplant"]

,需要以下输出:(数组,填充POST数据或空)

$saunterstuetzt
$sageplant
$osunterstuetzt
$osgeplant

变量数组名不工作…我得到错误:"in_array()[函数。in-array]:错误的数据类型为第二个参数",所以我猜它不会创建数组…

提前感谢您的帮助!Languste

我对php很陌生,所以我试着为这个目的做一个函数。

你真的不应该使用变量-变量。

这里有一个更干净、可重用的方法:

function get_post_param($param, $default = null) {
  return empty($_POST[$param]) ? $default : $_POST[$param];
}
$saunterstuetzt = get_post_param("saunterstuetzt", array());
$sageplant = get_post_param("sageplant", array());
$osunterstuetzt = get_post_param("osunterstuetzt", array());
$osgeplant = get_post_param("osgeplant", array());

不能返回具有特定名称的变量作为函数的返回值!