0

I have a somewhat complex HTML form that allows users to add and reorder rows (spaces) with subrows (walls).

My input fields look like this:

<input type="text" name="spaces[][space]">
<input type="text" name="spaces[][walls][][orientation]">

After working on this for 2 full days, I have managed to write the following code, which almost works:

$spaces_temp = [];
foreach ($_POST['spaces'] as $k => $v) {
    $val = intdiv($k, 2);
    $spaces_temp[$val][key($v)] = $v[key($v)];
}
$_POST['spaces'] = $spaces_temp;
$spaces = array_map(
    fn($space) => [
        "space" => $space['space'],
        "walls" => array_map(
            fn($wall) => [
                "orientation" => $wall['orientation'],
                "plastering" => $wall['plastering'],
                "color" => $wall['color'],
                "condition" => $wall['condition'],
                "finish" => $wall['finish'],
                "soiled" => $wall['soiled'],
                "comments" => $wall['comments'],
            ],
            $space['walls']
        ),
        "extra_information" => $space['extra_information'],
    ],
    $_POST['spaces'] ?? []
);

The first part of my code I got from another helpful answer here on SO.

I know that the number 2 in the intdiv($k,2) indicates that there would be 2 fields in the spaces array. This works fine as long as I don't add any walls. I know that I have 9 fields, but when I change this number to 9 not all fields seem to be added: strangely enough, only the fields space, walls>comments and extra_information are added to the database. Changing the number to anything between 2 and 9 causes empty spaces and walls to be added in the database.

How can I update this code so it correctly adds all rows and subrows to the database, in the correct order?

Andy Preston
  • 779
  • 4
  • 9
  • 23

0 Answers0