How to better organize the foreach

Asked

Viewed 92 times

2

I have this foreach which is working perfectly, but I think it’s a very polluted, very large code. Is there any way to rewrite this foreach in a more correct way? Everything works perfectly, but I am optimizing the code in a general way.

<?php

$dados = array(
   '<tr><td>ID: 120</td></tr>',
   '<tr><td>Classe de aferimento: Natural</td></tr>',
   '<tr><td>Área de atuação: Airsoft</td></tr>',
   '<tr><td>Valor de custo: R$ 1.220,50</td></tr>',
   '<tr><td>Local: Santa-Fé</td></tr>'
);

foreach ($dados as $value) {
    $valor = strip_tags(trim($value));
    $xpl = explode(":",$valor);

    $pos = strpos($xpl[0], "ID");
    if ($pos === false) {
    } else {
        $cltId = trim($xpl[1]);
    }

    $pos = strpos($xpl[0], "Classe");
    if ($pos === false) {
    } else {
        $cltClasse = trim($xpl[1]);
    }

    $pos = strpos($xpl[0], "Área");
    if ($pos === false) {
    } else {
        $cltArea = trim($xpl[1]);
    }

    $pos = strpos($xpl[0], "Valor");
    if ($pos === false) {
    } else {
        $cltValor = trim($xpl[1]);
        $cltValor = explode(" ", $cltValor);
        $cltValor = number_format($cltValor[1], 2, '.', '');
    }

    $pos = strpos($xpl[0], "Local");
    if ($pos === false) {
    } else {
      $cltLocal = trim($xpl[1]);
    }

}
echo "Dados a serem iseridos no Banco de Dados";
echo "<br />";
echo "ID do solicitante: ".$cltId;
echo "<br />";
echo "Classe do solicitante: ".$cltClasse;
echo "<br />";
echo "Área do solicitante: ".$cltArea;
echo "<br />";
echo "Valor cobrado: ".$cltValor;
echo "<br />";
echo "Local de ação: ".$cltLocal;
?>
  • What does the code do? What is the input and what is the output produced?

  • The input is that of the $data array and the output is individual each with a different variable that are the variables starting with $clt...

  • A variable $i is useless. Because you are using it?

  • Really @Maurydeveloper will edit to delete.

  • Where does that come from array? It will always be in that same format?

  • It will always be in the same format @Andersoncarloswoss . I made a Crawler from a site where this table already exists. I separated only the <tr>.

  • 1

    $pos = strpos($xpl[0], "ID");&#xA; if ($pos === false) {&#xA; } else {&#xA; $cltId = trim($xpl[1]);&#xA; } A suggestion to minimize this code: $pos = strpos($xpl[0], "ID");&#xA; if ($pos !== false) {&#xA; $cltId = trim($xpl[1]);&#xA; } It’s useless to use comparison if you don’t perform anything.

  • @Maurydeveloper Good! Already gave a diminished!!!

Show 3 more comments

3 answers

4


All rows in your table have the same pattern: <nome>: <valor>. So you can take advantage of this standard to simplify your code:

$resultado = [];

foreach ($dados as $dado) {
  list($nome, $valor) = explode(':', strip_tags($dado));
  $resultado[trim($nome)] = trim($valor);
}

Basically you go through the values of your array, removes HTML tags, splits in the colon character, :, and sets the first value as the column name and the second as the column value, saving in $resultado.

At the end you’ll have a array associative:

Array
(
    [ID] => 120
    [Classe de aferimento] => Natural
    [Área de atuação] => Airsoft
    [Valor de custo] => R$ 1.220,50
    [Local] => Santa-Fé
)

Can do:

echo <<<RESULTADO
Dados a serem iseridos no Banco de Dados
ID do solicitante: {$resultado["ID"]}
Classe do solicitante: {$resultado["Classe de aferimento"]}
Área do solicitante: {$resultado["Área de atuação"]}
Valor cobrado: {$resultado["Valor de custo"]}
Local de ação: {$resultado["Local"]}
RESULTADO;

See working on Repl.it

  • Gave improved 300%. Was legibly to view and save lines.

1

$titles = array('ID', 'Classe', 'Área', 'Valor', 'Local');
$resultado = array();

foreach ($dados as $value) {
    $valor = strip_tags(trim($value));
    $xpl = explode(":", $valor);

    if (in_array($xpl[0], $titles)) {

        $resultado[$xpl[0]] = trim($xpl[1]);

        if ($xpl[0] === 'Valor') {
            $cltValor = explode(" ", $resultado[$xpl[0]]);
            $resultado[$xpl[0]] = number_format($cltValor[1], 2, '.', '');
        }

    }
}

To display the values:

echo "Dados a serem inseridos no Banco de Dados";
echo "<br />";
echo "ID do solicitante: " . $resultado['ID'];
echo "<br />";
echo "Classe do solicitante: " . $resultado['Classe'];
echo "<br />";
echo "Área do solicitante: " . $resultado['Área'];
echo "<br />";
echo "Valor cobrado: " . $resultado['Valor'];
echo "<br />";
echo "Local de ação: " . $resultado['Local'];
  • That’s exactly it! However, the in_array only works if the values are exact. The above example only works with the ID and Local. But it has already given a lot of light. I will try to combine in_array with strpos. Know some solution for this?

  • Their values are not exact?

  • No. And it explodes returns "Requester class", for example. So the in_array returns false in_array($xpl[0], "Class").

-5

Yes, in the view of that list you can do it this way:

<table>
  <thead>
    <tr>
      <th>Id</th>
      <th>Nome</th>
      <th>Sexos</th>
    </tr>
</thead>
<tbody>
<?php foreach($dados as $dado) :?>
   <tr>
       <td><?=$dado->id?></td>
       <td><?=$dado->nome?></td>
       <td><?=$dado->sexo?></td>
   </tr>
<?php endforeach;?>
</tbody>
</table>

This way is more optimized the code PHP itself has this way of behavior to front-end, I hope I helped.

Taking data from a table with JS:

$(document).ready(function(){

   var tbody = $('tbody > tr > td');

   $.each(tbody, function(index, item){
       var item = $(item).text();
       var dados = item.replace(",", ".");
       console.log(dados);
       debugger;
   })
})
  • 1

    I’m sorry, what you’re saying doesn’t make any sense, and if you want to continue, I invite you to go into chat.

  • 2

    Please avoid long discussions in the comments; your talk was moved to the chat and can continue there if there is interest

Browser other questions tagged

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