Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
840 views
in Technique[技术] by (71.8m points)

forms - Submitting a multidimensional array via POST with php

I have a php form that has a known number of columns (ex. top diameter, bottom diameter, fabric, colour, quantity), but has an unknown number of rows, as users can add rows as they need.

I've discovered how to take each of the fields(columns) and place them into an array of their own.

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

So what I end up with in the HTML is:

<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.

What I would like to do now is take all the rows and columns put them into a multidimensional array and email the contents of that to the client (preferably in a nicely formatted table). I haven't been able to really comprehend how to combine all those inputs and selects into a nice array.

At this point, I'm going to have to try to use several 1D arrays, although I have the idea that using a single 2D array would be a better practice than using several 1D arrays.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

On submitting, you would get an array as if created like this:

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

However, I would suggest changing your form names to this format instead:

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

Using that format, it's much easier to loop through the values.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...