有人可以解释我如何解决以下问题:
function GetSetClearForm(){
$person = array('firstname' => $_POST["fname"], 'lastname' => $_POST["lname"],'age' => $_POST["age"] ,'city' => $_POST["city"] ,'zipcode' => $_POST["zcode"],'address' => $_POST["address"]);
print_r($person);
$personlist = array();
array_push($personlist,$person);
print_r($personlist);
return $personlist;
}
当print_r($personlist);
运行时,我得到以下输出:
Array (
[0] => Array (
[firstname] => 2
[lastname] => 2
[age] => 2
[city] => 2
[zipcode] => 2
[address] => 2
)
)
(填入所有带“2”的文本框)。
此时此操作还可以,但每当我填写另一个时,我都会收到此输出:
Array (
[0] => Array (
[firstname] => 1
[lastname] => 1
[age] => 1
[city] => 1
[zipcode] => 1
[address] => 1
)
)
(填入所有带“1”的文本框)。
因此,它不会在新索引(index[1]
)上创建其他人,而是用新人替换index[0]
并删除旧版本。我不希望它删除它我想得到一个人满贯的列表。我认为这与array_push
有关,但我不确定是否希望有人能帮助我。
修改
添加了index.php:
<form action="check.php" method="POST">
<table>
<tr><td>First name</td><td><input type="text" name="fname"></td></tr>
<tr><td>Last name</td><td><input type="text" name="lname"></td></tr>
<tr><td>Age</td><td><input type="text" name="age"></td></tr>
<tr><td>City</td><td><input type="text" name="city"></td></tr>
<tr><td>Zipcode</td><td><input type="text" name="zcode"></td></tr>
<tr><td>Adress</td><td><input type="text" name="address"></td></tr>
<tr><td></td><td><input type="submit" value="Submit"></td></tr>
</table>
</form>
添加了check.php
<?php
include("functions.php");
$personlist = array();
$personlist[] = GetSetClearForm();
print_r($personlist);
?>
答案 0 :(得分:2)
您可以使用:
而不是使用array_push$personlist = array();
$personlist[] = $person;
这样,每次“插入”新值时都会创建一个新索引,在本例中为数组。
修改强>
您需要在函数外声明并填充$ personlist数组。那说:
function GetSetClearForm(){
$person = array('firstname' => $_POST["fname"], 'lastname' => $_POST["lname"],'age' => $_POST["age"] ,'city' => $_POST["city"] ,'zipcode' => $_POST["zcode"],'address' => $_POST["address"]);
print_r($person);
return $person;
}
$personlist = array();
$personlist[] = GetSetClearForm();
答案 1 :(得分:0)
我认为问题是你每次调用函数时都会重新创建人员列表。也许你可以像这样解决它:
//Create your person list some where else and keep it alive.
//Like in a session?
session_start();
//Then give your keep alive array to your function each time.
function GetSetClearForm(){
$person = array('firstname' => $_POST["fname"], 'lastname' => $_POST["lname"],'age' => $_POST["age"] ,'city' => $_POST["city"] ,'zipcode' => $_POST["zcode"],'address' => $_POST["address"]);
print_r($person);
return $person;
}
$_SESSION['personlist'][] = GetSetClearForm() ;
print_r( $_SESSION['personlist']);