用php通过POST提交multidimensional array

我有一个具有已知数量的列(例如顶部直径,底部直径,结构,颜色,数量)的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. 

我现在想要做的是把所有的行和列放到一个multidimensional array中,并将其内容发送到客户端(最好是格式化好的表格)。 我还没有能够真正理解如何将所有这些input和select组合成一个不错的数组。

在这一点上,我将不得不尝试使用几个一维数组,虽然我有一个想法,使用单个二维数组将是比使用几个一维数组更好的做法。

在提交时,你会得到一个数组,就像这样创build:

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

不过,我build议将表单名称改为这种格式:

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

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

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

那么以后你做这样的事情:

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