使用循环以特定方式用sql数据填充表

时间:2019-09-22 20:47:44

标签: php html

我想以特定方式将以下数据库表中的数据放入html表中。

enter image description here

以下是我的php代码:

echo "<table style='border:2px solid black;width:100%;'>";

foreach ($results as $key => $value) {
  for ($i = 1; $i < 4; $i++) { // 3 + 1 = 4 (itération sur la valeur de $value['ligne'])
    if ($i == $value['ligne']) {
      echo "<tr>";
      for ($j = 1; $j < 4; $j++) { // itération sur la valeur de $value['colonne']
        //if ($j == $value['colonne'] ) {
        echo "<td style='padding:1em;border:1px solid black;'>".$value['contenu']."</td>";
        //}
      }
      echo "</tr>";
    }   
  }
}
echo "</table>";

这是我的输出:

enter image description here

我要实现的是仅在表的第1列中包含“ colonne1”;以同样的方式,“ Ligne1”应仅出现在第1行中;否则,“ colonne2”仅出现在第2列中。第2行中的“ Ligne2”是我能够执行的操作。任何想法?谢谢,谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用二维数组来实现所需的对象。

首先,根据数据库结果构建数据结构。

// assuming you’ve retrieved table into  $results
$table =array();
foreach($results as $v) {

  $row = $v[‘ligne’];
  $col = $v[‘colonne’];
  $content = $v[‘contenue’];

  $table[$row][$col] = $content;
}

// build html table
?>

然后您可以在视图中将其打印出来:

<table>
    <?php foreach($table as $row_array): ?>
    <tr>
        <?php foreach($row_array  as $col): ?>
            <td><?= $col ?></td>
        <?php endforeach; ?>
    </tr>
    <?php endforeach; ?>
</table>