提问人:aeran 提问时间:12/20/2008 最后编辑:Rahulaeran 更新时间:5/22/2019 访问量:12407
迭代多个 $_POST 数组
Iterating multiple $_POST arrays
问:
我有以下代码:
<tr>
<td width="60%">
<dl>
<dt>Full Name</dt>
<dd>
<input name="fullname[]" type="text" class="txt w90" id="fullname[]" value="<?php echo $value; ?>" />
</dd>
</dl>
</td>
<td width="30%">
<dl>
<dt>Job Title</dt>
<dd>
<input name="job_title[]" type="text" class="txt w90" id="job_title[]" value="<?php echo $value2; ?>" />
</dd>
</dl>
</td>
</tr>
假设我有几行上述代码。如何迭代并获取数组和的值?$_POST['fullname']
$_POST['job_title']
答:
10赞
Vinko Vrsalovic
12/20/2008
#1
它只是一个数组:
foreach ($_POST['fullname'] as $name) {
echo $name."\n";
}
如果问题是你想并行迭代两个数组,只需使用其中一个来获取索引:
for ($i=0; $i < count($_POST['fullname']); $i++) {
echo $_POST['fullname'][$i]."\n";
echo $_POST['job_title'][$i]."\n";
}
3赞
OIS
12/20/2008
#2
我之前删除了它,因为它非常接近 Vinko 的答案。
for ($i = 0, $t = count($_POST['fullname']); $i < $t; $i++) {
$fullname = $_POST['fullname'][$i];
$job_title = $_POST['job_title'][$i];
echo "$fullname $job_title \n";
}
原始索引不是 0 - N-1 之间的数字
$range = array_keys($_POST['fullname']);
foreach ($range as $key) {
$fullname = $_POST['fullname'][$key];
$job_title = $_POST['job_title'][$key];
echo "$fullname $job_title \n";
}
这只是一般信息。使用 SPL DualIterator,您可以制作如下内容:
$dualIt = new DualIterator(new ArrayIterator($_POST['fullname']), new ArrayIterator($_POST['job_title']));
while($dualIt->valid()) {
list($fullname, $job_title) = $dualIt->current();
echo "$fullname $job_title \n";
$dualIt->next();
}
评论
0赞
Vinko Vrsalovic
12/20/2008
DualIterator 有什么好处?
0赞
OIS
12/21/2008
它与 SPL 中的所有其他迭代器相似,因此对于那些使用迭代器的人来说,它很熟悉。我猜它也类似于那些习惯于 Java 的人。但我认为他们至少应该制作一个 MultiIterator 而不是一个有限的 DualIterator。
0赞
jmucchiello
12/20/2008
#3
Vinko 和 OIS 的答案都非常好(我提高了 OIS')。但是,如果您总是打印文本字段的 5 份副本,则始终可以专门命名每个字段:
<?php $i=0; while($i < 5) { ?><tr>
...
<input name="fullname[<?php echo $i; ?>]" type="text" class="txt w90" id="fullname[<?php echo $i; ?>]" value="<?php echo $value; ?>" />
评论
0赞
OIS
12/20/2008
这将产生与不命名它们相同的结果。
0赞
jmucchiello
12/20/2008
不完全是。用户可以在 name[1] 和 job[3] 中输入数据并点击提交。空数组将同时返回 name[0] 和 job[0]。(我不知道这对我的帮助有多大。
1赞
Imran
12/20/2008
#4
我认为您要解决的问题是从 $_POST['fullname'][] 和 $_POST['jobtitle'][] 中获取一对具有相同索引的值。
for ($i = 0, $rowcount = count($_POST['fullname']); $i < $rowcount; $i++)
{
$name = $_POST['fullname'][$i]; // get name
$job = $_POST['jobtitle'][$i]; // get jobtitle
}
评论
0赞
jmucchiello
12/20/2008
这个答案与上面OIS的答案相同。
0赞
Imran
12/20/2008
是的,我在发布答案后看到了它。
1赞
Zoredache
12/20/2008
#5
如果我理解正确的话,你有 2 个数组,你基本上希望并行迭代。
类似以下内容可能适合您。而不是 ,您将使用 和 。$a1
$a2
$_POST['fullname']
$_POST['jobtitle']
<?php
$a1=array('a','b','c','d','e','f');
$a2=array('1','2','3','4','5','6');
// reset array pointers
reset($a1); reset($a2);
while (TRUE)
{
// get current item
$item1=current($a1);
$item2=current($a2);
// break if we have reached the end of both arrays
if ($item1===FALSE and $item2===FALSE) break;
print $item1.' '. $item2.PHP_EOL;
// move to the next items
next($a1); next($a2);
}
评论