-1

我正在尝试从 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'];

但没有任何东西打印到页面上

4

1 回答 1

1

我不认为你可以$_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:

//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....

快乐编码!

于 2012-07-21T01:52:31.017 回答