考虑一个生成表单的 PHP 脚本,该表单看起来像一个表格,并且多次输出相同的重复行:
print('<form method="POST" action="index.php">
<table>
<tr>
<th>Row #</th>
<th><tt>name</tt></th>
<th><tt>value</tt></th>
</tr>');
for ( $i = 1; $i <= 4; $i++ )
{
print('<tr>
<th>' .$i. '</th>
<td><input type="text" name="name_' .$i. '" size="20"></td>
<td><input type="text" name="value_' .$i. '" size="4"></td>
</tr>');
}
print('</table>
<input type="submit" name="is_submit" value="Submit">
</form>');
当您提交此表单时,$_POST
数组将如下所示:
array (
'name_1',
'value_1',
'name_2',
'value_2',
'name_3',
'value_3',
'name_4',
'value_4',
'is_submit',
);
我想做的是组织这个输入,所以它看起来像这样:
array (
1 =>
array (
'name',
'value',
),
2 =>
array (
'name',
'value',
),
3 =>
array (
'name',
'value',
),
4 =>
array (
'name',
'value',
),
);
这意味着,以相同行 ID号结尾的每个字段都与两级深度数组中的其他字段(在同一行中)组合在一起。
我一直在涂鸦解决这个问题的选项,并提出了以下“解决方案”(有组织的数组(上图)实际上是$output
通过这种方法创建的转储):
if ( array_key_exists('is_submit', $_POST) ) // Form is submitted properly
{
unset($_POST['is_submit']); // Drop the status key
foreach ( array_keys($_POST) as $key )
{
$key_exploded = explode("_", $key); // [0] is key 'basename', [1] is the 'row ID'
$output[ $key_exploded[1] ][ $key_exploded[0] ] = $_POST[$key];
}
}
最大的问题是这种方法看起来有点混淆和硬编码。我认为并希望这里更高级的人可以指导我采用更动态的(那一unset
行很痒,我需要调用unset()
每个非表格行)和更好的方法。