Frontend data to structured field

Hi,

I have a form on the front end and it gets converted into a draft post. All goes fine except for the structured field data. I have looked at the Cookbook recipes for posting from the front end, and also this forum post: https://forum.getkirby.com/t/adding-frontend-form-post-data-to-a-structure-field/24550

No luck so far.

The form field is a table with several rows:

<tr>
   <td><input type="text" name="laser[]" value="" /></td>
   <td><input type="text" name="laserwave[]" value="" /></td>
</tr>

In the controller the data is fetched like this:

$laser = get('laser');
$laserwave = get('laserwave');

And put into the structured field like this:

$i = 0;
foreach ( $laser as $l ) {
  if ( "" != $l ) {
      $lasers = [
          'laser' => $l,
          'laserwave' => $laserwave[$i],
      ];
  }
  $i++;
}
$page->update([
    'lasers' => Data::encode([$lasers], 'yaml')
]);

The structured field blueprint is this:

            lasers:
                label: Lasers
                type: structure
                max: 5
                fields:
                    laser:
                        type: text
                    laserwave:
                        label: Laser wave (in Nm)
                        type: text

The result in the txt file is this:

Lasers:

- 
  laser: ""
  laserwave: ""
  0:
    laser: hello 3
    laserwave: "22"
  1:
    laser: ""
    laserwave: ""
  2:
    laser: ""
    laserwave: ""
  3:
    laser: ""
    laserwave: ""
  4:
    laser: ""
    laserwave: ""

----

Any ideas? I have run out of them.
Thanks.

// initialize an empty array
$lasers = [];
foreach ( $laser as $key => $l ) {
  if ( "" != $l ) {
     // first issue here, because you are adding to the same array, so append to array in the loop
      $lasers[] = [
          'laser' => $l,
          'laserwave' => $laserwave[$key],
      ];
  }
}
// second issue: the array shouldn't be wrapped in an array again
$page->update([
    'lasers' => Data::encode($lasers, 'yaml'),
]);

The additional counter is superfluous.

Amazing!
Thank you so much.