使用 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 数组更好。

原文由 Fireflight 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 674
2 个回答

提交时,您会得到一个数组,就像这样创建的:

 $_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>';
}

原文由 DisgruntledGoat 发布,翻译遵循 CC BY-SA 2.5 许可协议

@DisgruntledGoat 的回答是绝对正确的;但是,如果有人正在寻找未设置为必需的值,这意味着 $_POST === null 可能会发生,您将使用 isset() 条件如下:

 $placeHolderValue = "Incomplete";

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

这一切都使用@DisgruntledGoat 在他们的回答中提到的命名格式。

原文由 jpgerb 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题