1

考虑一个生成表单的 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()每个非表格行)和更好的方法。

4

2 回答 2

5

更改这些行:

<td><input type="text" name="name_' .$i. '" size="20"></td>
<td><input type="text" name="value_' .$i. '" size="4"></td>

<td><input type="text" name="foobar['.$i.'][name]" size="20"></td>
<td><input type="text" name="foobar['.$i.'][value]" size="4"></td>

$_POST['foobar'] 现在将具有所需的结构。

于 2012-07-09T08:38:20.540 回答
0

如果您不想更改表单,可以在 foreach 循环中引入一个附加条件:

if ( array_key_exists('is_submit', $_POST) ) // Form is submitted properly
{
    foreach ( array_keys($_POST) as $key )
    {
        $key_exploded = explode("_", $key); // [0] is key 'basename', [1] is the 'row ID'

        // check if keys start with 'name' or 'value'
        if ($key_exploded[0] == 'name' || $key_exploded[0] == 'value')
            $output[ $key_exploded[1] ][ $key_exploded[0] ] = $_POST[$key];
    }
}
于 2012-07-09T08:44:44.623 回答