2011-08-21 100 views
1

我有一个包含人名的MySQL表。 使用PHP,将这些名称分开并以3列显示的最佳方式是什么?将数据拆分为3列

这可以通过使用HTML表格来实现,但是仅仅使用<div>可以做到这一点吗?

我听说这可以使用%运算符完成。这是最好的方式吗?这将如何完成?

+0

什么是名称的格式,你想如何拆分它们? – DaveRandom

+7

你有没有考虑过接受答案? –

+2

当处理表格数据时,'

'没什么问题,你知道...... – DaveRandom

回答

8

你可以使用模运算符来实现这一点,但它实际上可能只用CSS。

使用display: inline-block,您可以获得良好的列效果。看看this JSFiddle here。我只使用JavaScript,因为我很懒;在您的情况下,PHP将生成<div>列表。如果你想限制它们到一定的宽度,只需将它们放在一个固定宽度的容器<div>中。


我想出了一个使用表的解决方案,这真的是你应该做的(你没有给出任何特殊用例)。代码如下,以及工作演示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秒。这里有一些CSS;这应该放在一个单独的文件中,不是内联的

<?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>"; 
?> 
+0

感谢你。理想情况下,我宁愿使用PHP和模数运算符来执行此操作,因为您应该可以定义每列中应包含多少项目,因此可以指定数据何时应该插入下一列。 你能提供一些关于如何做到这一点的指导吗? – user826855

+0

@ user826855请参阅我上面的编辑。代码应该相当自我解释(我希望)。如果你仍然有问题,不要害怕问。 – Bojangles

+0

非常好!感谢那。是否有可能让它以另一种方式去做?相反,填充它的行(水平),是否有可能通过列(垂直)? – user826855