如何在foreach循环中创建HTML表

时间:2015-12-17 14:41:53

标签: php html arrays

我需要创建一个包含三列的HTML表格:电子邮件,姓名,循环中的姓氏。

任何人都可以提示如何开始创作吗?

$i=0;
foreach($result as $r) {
  echo "<pre>";
  print_r( $i ." ". $r['aluno_email'] ."". " | ". $r['aluno_nome']
. " " .
$r['aluno_sobrenome'] . " | ". strtolower(trim(($r['aluno_nome'])))."_".strtolower(trim($r['aluno_sobrenome'])));
   echo "<pre>";
    $i++;
}

5 个答案:

答案 0 :(得分:6)

在循环外创建表和表头。

在循环中填充表体,然后关闭循环。

<table>
    <tr>
        <th>Email</th>
        <th>Name</th>
        <th>Last Name</th>
    </tr>
    <?php
    $i = 0;
    foreach ($result as $r) {
        echo "<tr>";
        echo "<td>" . $r['aluno_sobrenome'] . "</td><td>" . strtolower(trim(($r['aluno_nome']))) . "</td><td>" . strtolower(trim($r['aluno_sobrenome'])) . "</td>";
        echo "</tr>";

        $i++;
    }
    ?>
</table>

答案 1 :(得分:3)

循环结果,每个结果输出一行

echo '<table>';
foreach ($results as $r) {
   echo sprintf('<tr><td>%s</td><td>%s</td><td>%s</td></tr>', $r['email'], $r['name'], $r['last_name']);
}
echo '</table>';

答案 2 :(得分:1)

试试这个:

<?php 
$i = 0;
echo '<table>';
foreach ($result as $r) {
    echo "<tr><td>{$i}</td><td>{$r['aluno_email'}</td><td>{$r['aluno_nome']}</td></tr>";
    $i++;
}
echo '</table>';

答案 3 :(得分:1)

我通常首先检查结果,然后构建表格:

if ($result->num_rows > 0) {
     echo "<table>
           <tr>
               <th>Email</th>
               <th>Name</th>
               <th>LastName</th>
           </tr>";

I run my loop and output as long as I have results:

// output data of each row
     while($row = $result->fetch_assoc()) {
         echo "<tr>
                   <td>" . $row["Email"]. "</td>
                   <td>" . $row["Name"]. "</td>
                   <td>" . $row["LastName"]. "</td>
               </tr>";

     }
     echo "</table>";

答案 4 :(得分:0)

这是你怎么做的

 echo "<table>
            <tr><th>Email</th><th>Name</th><th>LastName</th></tr>";

            foreach($result as $val){
                echo "<tr><td>".$val['email']."</td><td>".$val['name']."</td><td>".$val['lastName']."</td><td>"</tr>";
            }
echo "</table>";