0

鉴于,

$required_fields = array('name', 'location', 'email');                               
foreach ($required_fields as $fieldname) {
    if (isset($_POST[$fieldname]) || !empty($_POST[$fieldname])) {      


        }

现在在 if 语句中,我需要类似的东西

$fieldname = $_POST[$fieldname]; 

所以我得到

$name = "name"、$location = "location" 和 $email = "email"

我试过 $fieldname = $_POST[$fieldname] 但它不起作用。我怎样才能动态地做到这一点?

4

4 回答 4

9

你这样做,

$$fieldname = $_POST[$fieldname]; 

这种$$表示法称为变量 variable

于 2012-12-25T15:47:00.510 回答
3

您可以为此使用extract 功能。要过滤数组,您可以使用array_diff 函数

于 2012-12-25T15:47:06.527 回答
1
$required_fields = array('name', 'location', 'email');
extract(array_intersect_keys($_POST, array_flip($required_fields)));

$required_fields仅当 $_POST 数组中存在时,这将为每个命名的变量创建局部变量。否则,变量将未定义。

array_flip
array_intersect_key
提取

于 2012-12-25T16:17:21.313 回答
-2

你也可以使用

eval("$".$fieldname."='".$_POST["fieldname"]."';");
于 2012-12-25T15:55:42.827 回答