将html表单数组传递给php文件

时间:2012-07-21 01:23:00

标签: php html arrays html-form-post

我正在尝试从html表单获取信息并将其作为数组传递给我的php文件

这是我的html表单的代码片段:

<form action ="upload.php" method="post">
    Name<input id= "n" type="text" name="info[name]" /><br />
    Address: <input id="a" type = "text" name="info[address]" /><br />
    City: <input id="c" type = "text" name="info[city]" /><br />
</form>

然后在我的php文件中我尝试打印内容:

$information = $_POST['info'];

echo $information['name'];

但没有任何内容打印到页面

1 个答案:

答案 0 :(得分:1)

我认为你不能这样做(直接用HTML将它全部推到一个单独的数组中(除了$_POST))。你必须在开始时做一些额外的PHP工作。

首先,为了所有神圣的爱,让你的HTML输入名称更清晰:

<form action ="upload.php" method="post">
Name<input id= "n" type="text" name="info_name" /><br />
Address: <input id="a" type = "text" name="info_address" /><br />
City: <input id="c" type = "text" name="info_city" /><br />
</form>

现在,对于PHP:

//this is how I would do it, simply because I don't like a bunch of if/elseifs everywhere..
//define all the keys (html input names) into a single array:
$infoKeys[0]='name';
$infoKeys[1]='address';
$infoKeys[2]='city';
//define your end array
$information=array();
//now loop through them all and if they're set, assign them to an array. Simple:
foreach ( $infoKeys as $val ){

if(isset($_POST['info_'.$val])){

$information[$val]=$_POST['info_'.$val];

}//end of isset

else{

$information[$val]=null;

}//end of no set (isset===false)

}//end of foreach

//now, when you want to add more input names, just add them to $inputKeys. 
//If you used the if/elseif ways, your doc would be plastered in ifs and elseifs. 
//So i personally think the looping through the array thing is neater and better. 
//but, feel free to change it, as I have a feeling I'll have allot of critics because of this method.

// anyway, that should do it. The var $information should be an array of all your 'info_' html inputs....

快乐的编码!