Whi*_*ity 1 php forms arrays optimization parsing
考虑一个生成表单的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>');
Run Code Online (Sandbox Code Playgroud)
提交此表单时,$_POST数组将如下所示:
array (
'name_1',
'value_1',
'name_2',
'value_2',
'name_3',
'value_3',
'name_4',
'value_4',
'is_submit',
);
Run Code Online (Sandbox Code Playgroud)
我想做什么,它组织这个输入所以它看起来像这样:
array (
1 =>
array (
'name',
'value',
),
2 =>
array (
'name',
'value',
),
3 =>
array (
'name',
'value',
),
4 =>
array (
'name',
'value',
),
);
Run Code Online (Sandbox Code Playgroud)
这意味着,以相同行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];
}
}
Run Code Online (Sandbox Code Playgroud)
最大的问题是这种方法看起来有点混淆和硬编码.我想并希望周围更高级的人可以指导我更动态(那unset行很痒,我需要调用unset()每个非表行)和更好的方法.
改变这些行:
<td><input type="text" name="name_' .$i. '" size="20"></td>
<td><input type="text" name="value_' .$i. '" size="4"></td>
Run Code Online (Sandbox Code Playgroud)
至
<td><input type="text" name="foobar['.$i.'][name]" size="20"></td>
<td><input type="text" name="foobar['.$i.'][value]" size="4"></td>
Run Code Online (Sandbox Code Playgroud)
$ _POST ['foobar']现在将具有所需的结构.