Printing values with foreach in three different html <td> values

Asked

Viewed 904 times

0

Good, guys. I want to list my database data in an HTML table, but this in three columns <td>, when I maxed this value, it would create one more line <tr>.

Example:

<?php
                    foreach($produtos as $produto):
                ?>
                <td>
                    <div class="item">
                        <img src="produtos/imagens/<?=$produto['imagem']?>" class="imagem_item">
                        <div class="espaco_nome">
                            <span class="titulo_item"><?=$produto['nome']?></span>
                        </div>
                        <span class="preco_item">R$ <?=$produto['preco']?></span>
                    </div>
                </td>
                <?php
                    endforeach;
                ?>

In this case, it would print everything in the same row of the table. How do I make it create three columns and then create one more row?

  • 9

    Related : http://answall.com/questions/61347/nova-linha-na-tabela-a-cada-3-colunas/61348

  • agree @Guilhermelautert but I have already left a reply.

1 answer

1


Just to use logic :)

<?php
                $i = 1;
                foreach($produtos as $produto):
                  if($i == 1) {
                     echo "<tr>";
                  }
                ?>
                <td>
                    <div class="item">
                        <img src="produtos/imagens/<?=$produto['imagem']?>" class="imagem_item">
                        <div class="espaco_nome">
                            <span class="titulo_item"><?=$produto['nome']?></span>
                        </div>
                        <span class="preco_item">R$ <?=$produto['preco']?></span>
                    </div>
                </td>
                <?php
                    if($i == 3)
                        echo "</tr>";
                        $i = 1;
                    } else {
                        $i++;
                    }
                    endforeach;
                    if ($i != 1) { echo "</tr>"; }
                ?>
  • It was exactly that Hiago ;) Thank you for your reply ;)

  • Arrange, as soon as possible mark as correct the answer.

Browser other questions tagged

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