我正在学习php并且无法理解如何将关联数组与用户输入结合使用。我最终需要通过键值对数组进行排序,但是现在我不知道我是否正确地进行了操作。本书中的示例没有显示如何获取用户输入并在数组中使用它只是预定值。有人可以帮助我,告诉我,如果我走在正确的轨道上。我知道我需要使用$ _POST方法来获取数组的信息,但我不知道如何使用它。当我上传我所拥有的内容时,我一直在收到错误
<HTML>
<HEAD>
<TITLE>Student Form</TITLE>
</HEAD>
<BODY>
<FORM METHOD="post" ACTION="final_project.php">
<P>Please enter your name: <INPUT TYPE="text" NAME="txtname" SIZE= 10></P>
<P>Please enter your id: <INPUT TYPE="text" NAME="txtid" SIZE= 10></P>
<P>Please enter your address: <INPUT TYPE="text" NAME="txtaddress" SIZE= 10></P>
<P>Please enter your cell phone number: <INPUT TYPE="text" NAME="txtcell" SIZE= 10></P>
<P>Please enter your Major: <INPUT TYPE="text" NAME="txtmajor" SIZE= 10></P>
<P>Please enter your E-mail address: <INPUT TYPE="text" NAME="txtemail" SIZE= 10></P>
<P><INPUT TYPE="submit" NAME="submit" VALUE="Submit"></P>
</FORM>
<?php
$txtname = $_POST['txtname'];
$txtid = $_POST['txtid'];
$txtaddress = $_POST['txtaddress'];
$txtcell = $_POST['txtcell'];
$array = array(txtname=>$txtname, txtid=>$txtid, txtaddress=>$txtaddress,
txtcell=>$txtcell);
for each ($txtid as $key => $array){
echo "Your first name is ".$txtname.", id number is ".$txtid[$key].", your address is
".$txtaddress.", phone number is ".$txtcell.".";
}
?>
</BODY>
</HTML>
新更新: $ txtname [0] = $ _POST ['txtname']; $ txtid [1] = $ _POST ['txtid']; $ txtaddress [2] = $ _POST ['txtaddress']; $ txtcell [3] = $ _POST ['txtcell']; $ txtmajor [4] = $ _POST ['txtmajor']; $ txtemail [5] = $ _POST ['txtemail'];
$student = array('txtname'=>$txtname, 'txtid'=>$txtid, 'txtaddress'=>$txtaddress,
'txtcell'=>$txtcell, 'txtmajor'=>$txtmajor, 'txtemail'=>$txtemail);
foreach ($student as $key => $txtname){
print_r ($student[$key]);
}
数组([0] =&gt; Amanda)数组([1] =&gt; 12)数组([2] =&gt;西大街123号)数组([3] =&gt; 888-888-8888)数组([4] =&gt; CIS)数组([5] =&gt; email@email.com)
我已经更新了代码。我无法正确打印出我的阵列。
我希望它是= Array([0] =&gt; Amanda)[1] =&gt; 12 [2] =&gt; 123西大街...)我做错了什么?
答案 0 :(得分:1)
PHP manual for "foreach"说是这样做的:
foreach (array_expression as $key => $value)
但你有这样的话:
for each ($txtid as $key => $array){ ... }
我的猜测是你要用这个代替整个部分:
foreach ($array as $key => $txtid ) {
echo "your $key is $txtid ";
}
答案 1 :(得分:0)
我认为没有必要在数组中获取信息,你可以这样做:
<?php
// your form
$txtname = $_POST['txtname'];
$txtid = $_POST['txtid'];
$txtaddress = $_POST['txtaddress'];
$txtcell = $_POST['txtcell'];
echo "Your first name is ".$txtname.", id number is ".$txtid[$key].", your address is
".$txtaddress.", phone number is ".$txtcell.".";
&GT;