2011-08-21 105 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