我正在处理一个包含很多复选框的表单。检查是否填写了所有必填字段会产生错误,我的表单会再次显示预先填写的给定数据(文本和复选框)。我的复选框可以分配给4个不同的主题,因此我为每个主题填充一个数组。
所以基本上我为每个主题获取$ _POST数据并从中创建一个数组。如果没有填充主题的Checkbox,我必须创建一个空数组,因为我需要一个数组才能使我的Checkbox得到预先检查(我使用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()[function.in-array]:第二个参数的数据类型错误”,所以我猜它不会创建数组..
提前感谢您的帮助! Languste
答案 0 :(得分:2)
我对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());
答案 1 :(得分:0)
您不能返回具有特定名称的变量作为函数的返回值!