我正在开发一个邀请系统,用户可以邀请一个或多个人担任其帐户的协调员。为了允许用户一次邀请多个人,只要用户点击加号,我就会使用mootools创建另一行字段。在我下面的例子中,我将仅使用两行,但如果他们愿意,他们可以邀请更多。
HTML
<table>
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>Email Address</td>
<td>Invites</td>
</tr>
</thead>
<tbody id="coords">
<tr id="row-1">
<td id="1-1"><input type="text" name="fname-1"></td>
<td id="1-2"><input type="text" name="lname-1"></td>
<td id="1-3"><input type="text" name="email-1"></td>
<td id="1-4"><input type="text" name="invites-1"></td>
<td id="1-5"><span id="minus-1" class="minus">( - )</span></td>
</tr>
<tr id="row-2">
<td id="2-1"><input type="text" name="fname-2"></td>
<td id="2-2"><input type="text" name="lname-2"></td>
<td id="2-3"><input type="text" name="email-2"></td>
<td id="2-4"><input type="text" name="invites-2"></td>
<td id="2-5"><span id="plus-2" class="plus">( + )</span></td>
</tr>
</tbody>
</table>
$ _ POST看起来像这样
Array
(
[fname-1] => David
[lname-1] => Last
[email-1] => email address
[invites-1] => 15
[fname-2] => Shirley
[lname-2] => Last
[email-2] => other email
[invites-2] => 10
[action] => invite
)
PHP解析就是这个
if (isset($_POST['action'])) {
$_SESSION['inviteCoordinators'] = $_POST;
$newCoordinators = array();
//loop through all fields
while(list($key,$value) = each($_SESSION['inviteCoordinators'])) {
if($key != 'action') {
list($field, $user) = explode("-",$key);
$newCoordinators[$user] = array (
$field => $value
);
}
}
}
我期待$ newCoordinators看起来像这样
Array
(
[1] => Array
(
[fname] => David
[lname] => Last
[email] => email address
[invites => 15
)
[2] => Array
(
[fname] => Shirley
[lname] => Last
[email] => other email
[invites => 10
)
但我得到的只是[1] [邀请] =&gt; 15和[2] [邀请] =&gt; 10.我认为我只是看到邀请,因为其他人被覆盖但我无法理解为什么会这样。我的解析有什么问题?或者,我该怎么做呢?
旁注,唯一必填字段是电子邮件地址。
答案 0 :(得分:6)
为什么不使用数组命名您的html表单元素?您可以使表单形成如下:
<table>
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>Email Address</td>
<td>Invites</td>
</tr>
</thead>
<tbody id="coords">
<tr id="row-1">
<td id="1-1"><input type="text" name="invites[1][fname]"></td>
<td id="1-2"><input type="text" name="invites[1][lname]"></td>
<td id="1-3"><input type="text" name="invites[1][email]"></td>
<td id="1-4"><input type="text" name="invites[1][invites]"></td>
<td id="1-5"><span id="minus-1" class="minus">( - )</span></td>
</tr>
<tr id="row-2">
<td id="1-1"><input type="text" name="invites[2][fname]"></td>
<td id="1-2"><input type="text" name="invites[2][lname]"></td>
<td id="1-3"><input type="text" name="invites[2][email]"></td>
<td id="1-4"><input type="text" name="invites[2][invites]"></td>
<td id="2-5"><span id="plus-2" class="plus">( + )</span></td>
</tr>
</tbody>
</table>
你会得到你的帖子数据格式如下:
Array
(
[invites] => Array
(
[1] => Array
(
[fname] => first1
[lname] => last1
[email] => test@test.com
[invites] => 2
)
[2] => Array
(
[fname] => first2
[lname] => last2
[email] => test2@test.com
[invites] => 5
)
)
)
然后你可以做类似的事情:
foreach($_POST['invites'] as $invite){
//process invite
echo "{$invite['fname']} {$invite['lname']} was invited. <br />";
}