Doubt: Scroll through a PHP Laravel multidimensional array

Asked

Viewed 338 times

-1

How to Optimize Traversing Data from the Laravel Multidimensional Array in the Controller and The Result Reflected in the View.

Example:

[{"item":"0","item_descricao_id":5,"sim_nao":null,"dt_validade":null,"pagina_documento":null,"observacao":null},
{"item":"1","item_descricao_id":6,"sim_nao":null,"dt_validade":null,"pagina_documento":null,"observacao":null},
{"item":"2","item_descricao_id":7,"sim_nao":null,"dt_validade":null,"pagina_documento":null,"observacao":null},
{"item":"3","item_descricao_id":8,"sim_nao":null,"dt_validade":null,"pagina_documento":null,"observacao":null},
{"item":"4","item_descricao_id":9,"sim_nao":null,"dt_validade":null,"pagina_documento":null,"observacao":null}]

Using the For function in the Controller the print result is an array line:

Code:

      for ($i = 0; $i < sizeof($item); $i++){
           $dataInsert = array( 
                       'item' => $item[$i], 
                       'item_descricao_id' => $item_descricao_id[$i], 
                       'sim_nao' => $sim_nao[$i], 
                       'dt_validade'=> $dt_validade[$i],
                       'pagina_documento' =>$pagina_documento[$i], 
                       'observacao' =>$observacao[$i]);
                     } 

Result of this function:

{"item":"0","item_descricao_id":"5","sim_nao":null,"dt_validade":null,"pagina_documento":null,"observacao":null}

In this case there is a PHP library that traverses the lines of array arrays?

1 answer

0


Applied solution was to create a variable ($cont) to count row of each array within the loop that will be reflected in the View.

Reference: Save items from a Checklist form in the database - Laravel

Follows code:

 $cont = 0; //contador de linhas para os arrays

   for ($i = 0; $i < count($item); $i++){
   $dataInsert = array( 
                 'item' => $item[$cont], 
                 'item_descricao_id' => $item_descricao_id[$cont], 
                 'sim_nao' => $sim_nao[$cont], 
                 'dt_validade'=> $dt_validade[$cont],
                 'pagina_documento' =>$pagina_documento[$cont], 
                 'observacao' =>$observacao[$cont]);      
            $cont++; 
         } 

  • In this case you could not use the sizeof($item) or even the $i ?

  • @Darlei Fernando Zillmer In this situation it was a mistake to edit the code for the answer. I used Count in this case. And as it was necessary to go through the other array in a single form it took another variable to go through the array.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.