Home >Backend Development >PHP Tutorial >How to Submit and Process Multidimensional Arrays via POST in PHP?

How to Submit and Process Multidimensional Arrays via POST in PHP?

DDD
DDDOriginal
2024-11-30 17:58:16774browse

How to Submit and Process Multidimensional Arrays via POST in PHP?

Submit Multidimensional Arrays via POST in PHP

When working with PHP forms that have multiple columns and rows of variable lengths, it's necessary to convert the input into a multidimensional array. Here's a solution to this challenge.

First, assign unique names to each column, for example:

<input name="topdiameter['+current+']" type="text">

This results in HTML similar to:

<tr>
  <td><input name="topdiameter[0]" type="text">

When the form is submitted, you'll obtain arrays like:

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

However, consider using the following format:

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

With this format, looping through the values becomes more efficient:

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

This solution allows you to easily handle multidimensional arrays submitted via POST forms in PHP.

The above is the detailed content of How to Submit and Process Multidimensional Arrays via POST in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn