PHP For loop with complex input array

268 Views Asked by At

Okay, I need some help here. I have a form where the user can add/remove some input fields. Those fields live in modals that are dynamically built using jQuery. This is my basic setup:

<!--The fields I'm building and capturing-->
<script>
...
  var fieldOne = '<input type="text" name="field'+groupCount+'[one]">';
  var fieldTwo = '<input type="text" name="field'+groupCount+'[two]">';
...
</script>

groupCount is set by incremental button clicks. If groupCount is zero, no fields exist. This results in a series of field1[one], field1[two], field2[one], field2[two], and so on.

The form these live in will (of course) post to a separate PHP file. I know I can assign PHP variables to each individual field, but that doesn't help for larger groups.

I assume I would use some sort of for loop to capture these field values, but don't have the slightest clue how. Any help would be greatly appreciated.

1

There are 1 best solutions below

0
Nathanael On

in your php you can use preg_match

$data = array();
foreach ( $_POST as $key => $value ) {
    $matches = array();
    if (preg_match('/^field(\d+)$/', $key, $matches)) {
        $data[$matches[1]][] = $value;
    }
}
var_dump($data);