咆哮:开
显示表格数据时,使用table 而不是浮动div。在禁用 css 的情况下查看页面时这将是有意义的。如果您使用浮动div,那么您的数据将一直向下显示。并非所有table 的使用都不好。人们经常非常讨厌table,所以使用浮动div。 Table 仅在用于页面布局时不好。
咆哮:关闭
当我需要用一些打开、关闭和中间的额外字符显示某些内容时,我会使用implode。这是一个例子:
$data = array('column 1', 'column 2');
$output = '<div>'.implode('</div><div>', $data).'</div>';
//result: <div>column 1</div><div>column 2</div>
您可以将其扩展到几乎任何东西。 Array 和 implode 是 php 多年来的强大功能。您永远不需要任何 if 来检查它是否是最后一个元素,然后插入结束字符,或者检查它是否是第一个元素,然后插入开始字符,或者在元素之间打印附加字符。
希望对您有所帮助。
更新:
我误读了所问的主要问题。对不起,咆哮;)
这是我在 2 列中显示数据的代码:
//for example, I use array. This should be a result from database
$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
//should be 12 month, but this case there are only 9 of it
for ( $i = 0; $i <= 5; $i++)
{
//here I do a half loop, since there a fixed number of data and the item for first column
$output = '<div class="left">'.$data[$i].'</div>';
if ( isset($data[$i+6] )
{
$output = '<div class="right">'.$data[$i+6].'</div>';
}
echo $output."\n";
}
//the result should be
//<div class="left">1</div><div class="right">7</div>
//<div class="left">2</div><div class="right">8</div>
//<div class="left">3</div><div class="right">9</div>
//<div class="left">4</div>
//<div class="left">5</div>
//<div class="left">6</div>
其他解决方案是使用 CSS 来格式化输出,因此您只需将 div 从上到下放置,然后 css 使父容器仅垂直放置 6 项,并将其余部分放在现有内容的右侧。我不太了解它,因为它通常由 css 设计师或我的客户提供。