1

谁能解释我如何解决以下问题:

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);
?>
4

2 回答 2

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();
于 2013-04-16T13:47:59.540 回答
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']);
于 2013-04-16T13:52:44.963 回答