将数据分为3列 [英] Split Data into 3 columns
问题描述
我有一个包含人名的MySQL表. 使用PHP,将这些名称分开并在3列中显示的最佳方法是什么.
I have a MySQL table that contains people's names. Using PHP, what's the best way of dividing these names up and displaying them in 3 columns.
这可以使用HTML表来实现,但是是否可以仅使用<div>
来实现呢?
This could be achieved using an HTML table, but would it be possible to do this using only <div>
's?
我听说可以使用%运算符完成此操作.这将是最好的方法吗?该怎么做?
I heard that this can be done using the % operator. Would this be the best way, and how would this be done?
推荐答案
您可以使用模数运算符执行此操作,但是实际上只有CSS才有可能.
You could do this using the modulus operator, however it's actually possible with just CSS.
使用display: inline-block
,可以获得良好的列效果.在此处此JSFiddle中查看.我只使用JavaScript是因为我很懒.在您的情况下,<div>
列表将由PHP生成.如果要将它们限制为一定的宽度,只需将它们放入具有固定宽度的容器<div>
中即可.
Using display: inline-block
, you can get a good column effect. Take a look at this JSFiddle here. I'm only using JavaScript because I'm lazy; the <div>
list would be generated by PHP in your case. If you want to confine them to a certain width, just put them in a container <div>
with a fixed width.
我想出了一个使用表的解决方案,这确实是您应该做的(您没有给出任何特殊的用例).下面是代码,以及此处的有效演示.
I've come up with a solution using tables, which is really what you should be doing (you haven't given any special use cases). The code is below, as well as a working demo here.
$columns = 4; // The number of columns you want.
echo "<table>"; // Open the table
// Main printing loop. change `30` to however many pieces of data you have
for($i = 0; $i < 30; $i++)
{
// If we've reached the end of a row, close it and start another
if(!($i % $columns))
{
if($i > 0)
{
echo "</tr>"; // Close the row above this if it's not the first row
}
echo "<tr>"; // Start a new row
}
echo "<td>Cell</td>"; // Add a cell and your content
}
// Close the last row, and the table
echo "</tr>
</table>";
最后,我们有以列为中心的布局,这一次要回到div
s.这里有一些CSS.应当将其放在一个单独的文件中,不要内联.
And to finish off, we have our column-centric layout, this time going back to div
s. There's some CSS here; this should be put in a separate file, not left inline.
<?php
$rows = 10; // The number of columns you want.
$numItems = 30; // Number of rows in each column
// Open the first div. PLEASE put the CSS in a .css file; inline used for brevity
echo "<div style=\"width: 150px; display: inline-block\">";
// Main printing loop.
for($i = 0; $i < $numItems; $i++)
{
// If we've reached our last row, move over to a new div
if(!($i % $rows) && $i > 0)
{
echo "</div><div style=\"width: 150px; display: inline-block\">";
}
echo "<div>Cell $i</div>"; // Add a cell and your content
}
// Close the last div
echo "</div>";
?>
这篇关于将数据分为3列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!