Treat a POST array from a table

0

Good evening, my dear ones.

I'm having a hard time dealing with some data. I created a table, where <td> are fed dynamically when passing through a foreach like this:

<table class="table table-striped table-bordered" id="tb-despesas">
    <thead>
        <tr>
           <th>Conta(s)</th>
           <th>Valor Cobrar</th>
           <th>Valor Real</th>
           <th>Referente</th>
           <th>Consumo</th>
           <th>Medidas</th>
           <th>Obs.</th>
        </tr>
    </thead>
    <tbody>
       <?php
            foreach($Despesas->getResult() as $Despesa):
            extract($Despesa);
       ?>
       <tr>
           <td name="nm_nome"><?=$nm_nome?></td>
           <td><input name="vl_valor[]" class="form-control" type="number"></td>
           <td><input name="vl_valorreal[]" class="form-control" type="number"></td>
           <td><input name="referente[]" id="dt" class="form-control" type="month"></td>
           <td><input name="consumo[]" class="form-control" type="text"></td>
           <td><input name="medidas[]" class="form-control" type="text"></td>
           <td><input name="obs[]" class="form-control" type="text"></td>
       </tr>
       <?php
          endforeach;
       ?>
    </tbody>
</table>

At this stage, because of a class I have that does the insert into the database by array, I needed to get this as:

array
   0 =>
     'vl_valor' => '123',
     'vl_valorreal' => '123',
     'referente' => '2018-11'
   1 =>
     'vl_valor' => '456',
     'vl_valorreal' => '456',
     'referente' => '2018-11'

But what I end up getting in my $ _POST is something different because it puts everything together. It ends up like this:

array
  'vl_valor' => 
    array (size=74)
      0 => string '1234' (length=4)
      1 => string '2345' (length=4)
  'vl_valorreal' => 
    array (size=74)
      0 => string '1234' (length=4)
      1 => string '2345' (length=4)

Can anyone give me a light, how can I handle it? I wanted to do some foreach for every line I could find an insert in the database

    
asked by anonymous 03.11.2018 / 00:29

1 answer

1

One solution to this is to rearrange the array to the form you're already expecting, see how it would look:

function reorganizaArray($arr) {
    $arrOrganizado = [];
    for ($i = 0; $i < count($arr['vl_valor']); $i++) {
        $temp = [];
        foreach ($arr as $key => $value) {
            $temp[$key] = $value[$i];
        }
        $arrOrganizado[] = $temp;
    }
    return $arrOrganizado;
}
  

See working at Ideone .

    
03.11.2018 / 01:54