php 获取帖子变量的名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7163815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:10:45  来源:igfitidea点击:

get name of a post variable

phppost

提问by SmootQ

Possible Duplicate:
PHP $_POST print variable name along with value

可能重复:
PHP $_POST 打印变量名和值

I have a form (whatever number of fields).. this form will send $_POST data.. I want to return every $_POST variable value and name.

我有一个表单(无论字段数如何)。这个表单将发送 $_POST 数据。我想返回每个 $_POST 变量值和名称。

I wanna do soemthing like this :

我想做这样的事情:

foreach($_POST as $field){
    //****some code*****//
}

in a way that will display the fields and values like this:

以某种方式显示字段和值,如下所示:

name : Simo Taqi
email : [email protected]

姓名:西蒙塔奇
邮箱:[email protected]

in other words :

换句话说 :

if I have a post variable : $_POST['city']='las vegas'

如果我有一个帖子变量:$_POST['city']='las vegas'

I want to know how to get the name of the variable : 'city'.

我想知道如何获取变量的名称:'city'。

回答by Jimmy Sawczuk

$_POSTis populated as an associative array, so you can just do this:

$_POST填充为关联数组,因此您可以这样做:

foreach ($_POST as $name => $val)
{
     echo htmlspecialchars($name . ': ' . $val) . "\n";
}

Additionally, if you're just interested in the field names, you can use array_keys($_POST);to return an array of all the keys used in $_POST. You can use those keys to reference values in $_POST.

此外,如果您只对字段名称感兴趣,您可以使用array_keys($_POST);返回一个包含$_POST. 您可以使用这些键来引用$_POST.

foreach (array_keys($_POST) as $field)
{
    echo $_POST[$field];
}

回答by aorcsik

Use the extended foreach syntax:

使用扩展的 foreach 语法:

foreach ($_POST as $key => $value)
{
    echo $key . ": ". $value . "\n"; 
}

回答by George Velez

I disagree with this post, since it assumes that output is always intended for a browser. One should not get into the habit of this. \n is the correct usage and can be easily converted before output ( to a browser ) using the nl2br() function.

我不同意这篇文章,因为它假设输出总是针对浏览器的。人们不应该养成这种习惯。\n 是正确的用法,可以在输出(到浏览器)之前使用 nl2br() 函数轻松转换。