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

How to Efficiently Submit and Retrieve Multidimensional Arrays via POST in PHP?

DDD
Release: 2024-12-03 16:37:16
Original
275 people have browsed it

How to Efficiently Submit and Retrieve Multidimensional Arrays via POST in PHP?

Submitting Multidimensional Arrays via POST with PHP

In many scenarios, we encounter forms with varying numbers of rows and predefined columns. Users can freely add rows as needed. Understanding how to capture these dynamic inputs into a usable format is crucial.

Consider a form with columns for product attributes such as top diameter, bottom diameter, fabric, color, and quantity. While the number of columns remains constant, the number of rows is dynamic.

Constructing the Form

To accommodate a dynamic number of rows, we assign unique names to each field in each row using an array index. For instance:

<input name="topdiameter[0]" type="text">
Copy after login

This results in HTML that looks like this:


  <input name="topdiameter[0]" type="text">
Copy after login

Retrieving the Input Data

Upon form submission, the input data is accessible through the $_POST superglobal. It appears as an array of arrays:

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

Using a Multidimensional Array

Rather than using multiple one-dimensional arrays, it's more efficient to employ a single two-dimensional array. To achieve this, we modify the form name format:

name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...
Copy after login

With this revised format, we can now traverse the values easily:

if (isset($_POST['diameters'])) {
    echo '<table>';
    foreach ($_POST['diameters'] as $diam) {
        // Here, $diam['top'] and $diam['bottom'] are accessible
        echo '<tr>';
        echo '  <td>', $diam['top'], '</td>';
        echo '  <td>', $diam['bottom'], '</td>';
        echo '</tr>';
    }
    echo '</table>';
}
Copy after login

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template