2013-05-10 199 views
0

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

所以基本上我把每个主题的$ _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()[function.in阵列]:对于第二个参数错误的数据类型”,所以我想它不创建阵列...

感谢您的帮助提前! Languste

+1

'in_array()'在示例代码中未使用。请分享更多的代码。 – powtac 2013-05-10 13:00:55

+0

你的函数可以简化为:'return!empty($ _ POST [$ topic])? $ _POST [$ topic]:array();'。你在做什么只是一个非常复杂的方式来做到这一点。这也没有意义,因为你没有对返回值做任何事情。 – deceze 2013-05-10 13:02:23

回答

2

I'm quite new to php so I tried to make a function for this purpose.

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

这里有一个更清洁,可重复使用的方法:

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()); 
+0

谢谢!你的方法就像一个魅力。 – user2370021 2013-05-10 13:13:39

0

不能作为函数的返回与特定名称返回一个变量!