使用 php 通过 POST 提交多维数组

我有一个php表单,它具有已知数量的列(例如顶部直径,底部直径,织物,颜色,数量),但具有未知的行数,因为用户可以根据需要添加行。

我已经发现了如何获取每个字段(列)并将它们放入自己的数组中。

<input name="topdiameter['+current+']" type="text" id="topdiameter'+current+'" size="5" />
<input name="bottomdiameter['+current+']" type="text" id="bottomdiameter'+current+'" size="5" />

因此,我在HTML中最终得到的是:

<tr>
  <td><input name="topdiameter[0]" type="text" id="topdiameter0" size="5" /></td>
  <td><input name="bottomdiameter[0]" type="text" id="bottomdiameter0" size="5" /></td>
</tr>
<tr>
  <td><input name="topdiameter[1]" type="text" id="topdiameter1" size="5" /></td>
  <td><input name="bottomdiameter[1]" type="text" id="bottomdiameter1" size="5" /></td>
</tr>

...and so on.

我现在想做的是将所有行和列放入多维数组中,并将其内容通过电子邮件发送给客户端(最好是格式良好的表格)。我无法真正理解如何将所有这些输入和选择组合成一个漂亮的数组。

在这一点上,我将不得不尝试使用几个1D数组,尽管我有一个想法,使用单个2D数组比使用几个1D数组更好。


答案 1

提交时,您将获得一个数组,就像这样创建:

$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );

但是,我建议将表单名称更改为以下格式:

name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...

使用这种格式,循环遍历值要容易得多。

if ( isset( $_POST['diameters'] ) )
{
    echo '<table>';
    foreach ( $_POST['diameters'] as $diam )
    {
        // here you have access to $diam['top'] and $diam['bottom']
        echo '<tr>';
        echo '  <td>', $diam['top'], '</td>';
        echo '  <td>', $diam['bottom'], '</td>';
        echo '</tr>';
    }
    echo '</table>';
}

答案 2

您可以使用这样的命名提交所有参数:

params[0][topdiameter]
params[0][bottomdiameter]
params[1][topdiameter]
params[1][bottomdiameter]

然后你再做这样的事情:

foreach ($_REQUEST['params'] as $item) {
    echo $item['topdiameter'];
    echo $item['bottomdiameter'];
}

推荐