在页面中布局数据列表的最佳方法

时间:2014-10-06 09:27:55

标签: php html css

我理想地使用foreach循环在PHP中返回数据库结果,我想将结果集放在三列中。

<?php 
foreach ($departments as $department) { ?>
    <br />
    <input type="checkbox" name="departments[]" 
       value="<?php echo $department->id; ?>">
    <label><?php echo $department->name; ?></label>
<?php 
} ?>

目前,这只是在单个垂直线中列出结果集。我可以选择跨页面列表的哪些选项?我猜猜某种形式的HTML表格或CSS?什么是将其纳入PHP foreach循环的最佳方法?

3 个答案:

答案 0 :(得分:1)

列表或表格可以。对于表格使用

  <table>
  <tr>
  <?php foreach ($departments as $department): ?>
  <td>
  <input type="checkbox" name="departments[]" value="<?php echo $department->id; ?>">
  <label><?php echo $department->name; ?></label>
  </td>
  <?php endforeach; ?>
  </tr>
  </table>

答案 1 :(得分:1)

表格并不是真正的解决方案。由于复选框的数量不是常量,因此您不能使用固定的表结构而不使用javascript开销来正确对齐它们。列表可能是一个很好的解决方案。

更好的解决方案是使用float: left

的div
<?php foreach($departments as $department) { ?>
    <div class="width-4">
        <input type="checkbox" name="departments[]" value="<?php echo $department->id; ?>" />
        <span><?php echo $department->name; ?></span>
    </div>
<?php } ?>
<div style="clear: both"></div>

此处,width-4是有助于对齐复选框的div。 CSS如下所示。

.width-4 {
    width: 25%;
    float: left;
}

如果要在width-4内/内添加填充,边距或边框,请务必小心。在这种情况下,您需要在width-4内使用另一个容器div,并为其添加填充,边框或边距。

此布局的优点是,在4个复选框后,后续复选框会自动移至下一行。这些可以通过样式width-4轻松设置样式。

答案 2 :(得分:0)

只需列出一个清单:)

<强> HTML

<ul class="departments">
<?php foreach ($departments as $department) { ?>
    <li>
        <input type="checkbox" name="departments[]" value="<?php echo $department->id; ?>">
        <label><?php echo $department->name; ?></label>
    </li>
<?php } ?>
</ul>

<强> CSS

ul.departments li {
    display: inline-block;
}

请参见此处示例: http://jsfiddle.net/7a88w1vb/

相关问题