问题描述
我在 PHP 中有一个 POST,我并不总是知道我将要处理的变量字段的名称.
I have a POST in PHP for which I won't always know the names of the variable fields I will be processing.
我有一个函数可以循环遍历这些值(但是我也想捕获与之相关的变量名称.)
I have a function that will loop through the values (however I would also like to capture the variable name that goes with it.)
foreach ($_POST as $entry)
{
print $entry . "<br>";
}
一旦我弄清楚如何获取变量名称,我还需要弄清楚如何使函数足够智能,以检测并遍历存在变量的数组(即,如果我有一些复选框值.)
Once I figure out how to grab the variable names, I also need to figure out how I can make the function smart enough to detect and loop through arrays for a variable if they are present (i.e. if I have some checkbox values.)
推荐答案
如果您只想打印整个 $_POST 数组以验证您的数据是否正确发送,请使用 print_r:
If you just want to print the entire $_POST array to verify your data is being sent correctly, use print_r:
print_r($_POST);
递归打印数组的内容:
printArray($_POST);
function printArray($array){
foreach ($array as $key => $value){
echo "$key => $value";
if(is_array($value)){ //If $value is an array, print it as well!
printArray($value);
}
}
}
对嵌套数组应用一些填充:
Apply some padding to nested arrays:
printArray($_POST);
/*
* $pad='' gives $pad a default value, meaning we don't have
* to pass printArray a value for it if we don't want to if we're
* happy with the given default value (no padding)
*/
function printArray($array, $pad=''){
foreach ($array as $key => $value){
echo $pad . "$key => $value";
if(is_array($value)){
printArray($value, $pad.' ');
}
}
}
is_array 如果给定变量是数组,则返回 true.
is_array returns true if the given variable is an array.
您也可以使用 array_keys 返回所有字符串名称.
You can also use array_keys which will return all the string names.
这篇关于打印 $_POST 变量名和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!