如何在HTML表单内创建一组项目的数组 [英] How to create an array of a group of items inside an HTML form
问题描述
我正在尝试按照以下方式创建表单(我知道这不是有效的HTML,但是希望可以说明执行此操作的原因和原因):
I'm trying to create a form along the lines of the following (I am aware that this is not valid HTML, but it hopefully illustrates what and why I am trying to do this):
<form method="post" action="test.php">
<input type="text" name="teamName">
<br />Players:
<grouping name="players[]">
<input type="text" name="firstName"><br />
<input type="text" name="lastName"><br />
</grouping>
<input type="submit" value="submit">
</form>
通过javascript,然后我将根据需要多次添加分组元素.提交表单后,我可以按以下方式访问分组元素中的项目:
Through javascript, I would then add the grouping element as many times as needed. When the form is submitted, I could then access the items in the grouping element as follows:
foreach ($players as $player) {
$fName = $player->firstName;
$lName = $player->lastName;
}
也就是说,在我开始之前,我不知道团队中会有多少名球员,但是我知道一名球员的样子.我希望将所有内容都保留在一个屏幕上,以便用户可以在一页上将球员添加到他们的团队中,并且我希望能够将字段分组添加为一个组.但是,我也希望将分组存储为数组,而不是像这样:
That is, before I start, I don't know how many players will be on the team, but I know what a player looks like. I want to keep this all on one screen, so that the user can add players to their team on one page, and I want to be able to add the grouping of fields as a group. However, I would also like that grouping to be stored as an array, instead of doing something like:
<form method="post" action="test.php">
<input type="text" name="teamName">
<br />Players:
<input type="text" name="firstName[]"><br />
<input type="text" name="lastName[]"><br />
<input type="submit" value="submit">
</form>
这意味着我可以遍历分组中的各个元素,但不能遍历整个分组.
which would mean that I could iterate through the individual elements in the grouping, but not through the grouping as a whole.
有什么想法可以实现这一目标吗?
Any ideas how I might accomplish this?
推荐答案
不过,看看您的结构,我建议您使用更健壮的数组结构:
Looking at your structure, though, I'd recommend going for a more robust array structure:
foreach ($players as $i => $player) {
$fName = $player->firstName;
$lName = $player->lastName;
echo '<input type="text" name="players['.$i.'][firstName]" value="'.$fName.'" />';
echo '<input type="text" name="players['.$i.'][lastName]" value="'.$lName .'" />';
}
提交时,您将获得:
players => Array(
[0] => Array (
firstName => a name,
lastName => another name,
),
[1] => Array (
firstName => a name,
lastName => another name,
),
etc...
)
或者,您可以在最后一个输入字段中增加$ i ++,而不是在foreach语句中生成$ i,但是出于调试目的,通常很高兴知道从原始数组中使用哪个索引.
Alternatively, rather than generating $i in the foreach statement, you could do an incrementing $i++ in the last input field, but I find for debugging purposes it's often nice to know which index your using from the original array.
我建议在您的问题示例中使用此方法,因为它还允许您通过$ _POST ['players']
I recommend this approach over your question's example, as it also allows you to do a count/iterate through $_POST['players']
希望这会有所帮助
这篇关于如何在HTML表单内创建一组项目的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!