如何在三个较短的列中显示长列表?

时间:2012-12-08 20:23:30

标签: php html-table

有没有办法修改这个PHP代码

    foreach ($categories as $category)    
    {
        print("<tr>");               
        print("<td><a href=\"category.php?category=" . $category["id"] . "\">{$category["category"]}</a></td>");            
        print("</tr>");    
    }

以三个较短的列显示内容而不是一个非常长的列?像这里http://www.registrar.fas.harvard.edu/courses-exams/courses-instruction

显示顺序必须如下:

1 4 7
2 5 8 
3 6 9

4 个答案:

答案 0 :(得分:1)

您需要在每个行标记中使用3个单元格标记:

$cols = 3;
$col = 0;
foreach ($categories as $category)    
{
    if($col == 0)
        print("<tr>");            
    if($col < $cols) {
        print("<td><a href=\"category.php?category=" . $category["id"] . "\">{$category["category"]}</a></td>"); 
        $col++;
    } else {
        print("</tr>");  
        $col = 0;
    }  
}
if($col != 0)
    print("</tr>");

答案 1 :(得分:0)

$i=1;
foreach ($categories as $category)    
{
    if($i==1) {
      print("<tr>");  
    }             
    print("<td><a href=\"category.php?category=" . $category["id"] . "\">{$category["category"]}</a></td>");  
    if($i==3) {       
       print("</tr>"); 
       $i=1; 
    }
    $i++;  
}

答案 2 :(得分:0)

这将列出如下:

//    0,1,2
//    3,4,5

echo '<table><tr>';
foreach ($categories as $k=>$category){
    if($k%3==0 && $k!=0){
        echo '</tr><tr>';
    }
    echo '<td><a href="category.php?category='.$category["id"].'">'.$category["category"].'</a></td>';

}
echo '</table>';

答案 3 :(得分:0)

假设$ categories是一个数组。

$columns = 3;
$rows = ceil( sizeof( $categories ) / $columns );
echo "<table>\n";    
for ( $row = 1; $row <= $rows; $row++ )    
{
    echo "<tr>\n";  
    for ($column = 1; $column <= $columns; $column++) {
        $p = (($column - 1) * $rows) + $row - 1;
        $value = sizeof($categories) > $p ? $categories[$p] : '&nbsp;';
        echo "<td>{$value} {$p}</td>\n";
    }
    echo "</tr>\n";
 }
echo "</table>";

订单将

1 4 7
2 5 8 
3 6 9