动态行垂直向下并在六行之后创建列


Dynamic Rows Going Vertically Down and Create Column after Six Rows

我正在尝试创建这样的动态行:

[1] [7][13]

[2] [8][14]

[3] [9][15]

[4] [10]

[5] [11]

[6] [12]

目前,我有这样的输出:

[1] [2][3]

[4] [5][6]

[7] [8][9]

[10] [11][12]

[13] [14][15]

在创建另一列之前,我希望按字母/数字顺序向下输出6行。下面的代码用于在一行中创建3个数据,然后为另外3个数据创建另一行,依此类推。很抱歉无法附加我想要输出的图像。

<?php
$query = "SELECT name FROM categories WHERE parent_id=1 ORDER BY order_id ASC";
$result = mysql_query($query) or die ("Query failed");
$numrows = (mysql_num_rows ($result));

if($numrows >0){
echo "<table width = 100% border = '0' cellspacing = '2' cellpadding = '0'><tr>";
for ( $i = 0; $i <= 3; $i++) 
{
    echo "<td width='33%'>";
    while ($friendList = mysql_fetch_array($result)){
     $end = '<div class="left">'.$friendList['name'].'</div>'; 
      if ( isset($friendList[$j+6] )) 
      { 
        $end = '<div class="right">'.$friendList[$j+6].'</div>'; 
      } 
     echo $end."'n"; 
    }
    echo "</td>";
}
echo $end."</tr></table> ";
}
?>

谢谢。

由于您知道返回的行数$numrows,那么您可以利用它来预构建表,并在完成记录循环后进行组装。

$maxRows = 6;
$numCols = ceil($numRows / $maxRows);

在构建表的过程中,您将遍历返回的值,并将输出分配给数组。添加完所有记录后,您将组装并输出该表。

注意:您需要确保您的记录在查询中得到了适当的排序,因为编号仅用于索引

<?php
$numRows = 41;
$maxRows = 6;
$numCols = ceil($numRows / $maxRows);
$records = array();
for($i=1; $i <= $maxRows; $i++){
    $records[$i] = array();
}
for($i=1; $i <= $numRows; $i++){
    $row = ($i % $maxRows == 0 ? $maxRows : $i % $maxRows);
    $records[$row][]  = "[$i]";
}
$table = ['<table>'];
for($i=1; $i <= count($records); $i++){
    $row = ['<tr>'];
    $col = $records[$i];
    for($j=0; $j < count($col); $j++){
        /*
         * Begin modification area:
         * 
         * You would change the value of $col[$j] to reflect the desired 
         * output within each cell.
         */
         $output = $col[$j];
        /* End modification area */
         $row[$j+1] = '<td>' . $output . '</td>';
    }
    array_push($row, '</tr>');
    $table[$i] = implode('', $row);
}
$table[$i++] = '</table>';
echo implode('', $table);
?> 

输出:

[1] [7]  [13] [19] [25] [31] [37] 
[2] [8]  [14] [20] [26] [32] [38] 
[3] [9]  [15] [21] [27] [33] [39] 
[4] [10] [16] [22] [28] [34] [40] 
[5] [11] [17] [23] [29] [35] [41] 
[6] [12] [18] [24] [30] [36]