根据总计数动态循环列而不是行

时间:2018-06-04 20:01:19

标签: php loops foreach

我知道这涉及一个循环。我已经完成了很多搜索,但无法弄清楚。

我使用以下代码输出每行3项的数据。我真正想知道如何做的是让它们按列而不是按行升序,但动态地取决于查询中的记录数,而不是定义列中的行数。

<?php
define('DB_SERVER', "xxx");
define('DB_USER', "xxx");
define('DB_PASSWORD', "xxx");
define('DB_TABLE', "xxx");

$row_count = 0;

// The procedural way
$mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_TABLE);
$mysqli->set_charset("utf8");
$mysqli->query("SET NAMES 'utf8'");
if (mysqli_connect_errno($mysqli)) {
    trigger_error('Database connection failed: '  . mysqli_connect_error(), E_USER_ERROR);
}

$query = "
    SELECT lvm.luchtvaartmaatschappij, COUNT(*) AS CountLVMPhotos
    FROM tbl_photos p 

    LEFT JOIN tbl_luchtvaartmaatschappij lvm
    ON p.img_lvm = lvm.IATACode

    WHERE p.img_creator IN ('Daniël E. Cronk','Daniel E. Cronk')

    GROUP BY lvm.luchtvaartmaatschappij
    ORDER BY lvm.luchtvaartmaatschappij ASC ";

$result = mysqli_query($mysqli, $query) or trigger_error("Query Failed! SQL: $query - Error: ". mysqli_error($mysqli), E_USER_ERROR);

echo "
<table id='fotosBij' class='tablesorter-dropbox table-responsive ui-table-reflow'>";
echo "<tbody>";

if($result) {
    while($row = mysqli_fetch_assoc($result)) {
$items_in_row = 3 ;
$index = 0 ;   

echo '<tr >';

while($row = mysqli_fetch_assoc($result)){ 
 $index++ ;

echo "<td width='250px' valign='top'>" . $row['luchtvaartmaatschappij'] . "</td>";
echo "<td width='50px' valign='top'>" . $row['CountLVMPhotos'] . "</td>";
echo "<td width='80px'>&nbsp;</td>";

if ($index%$items_in_row == 0){
echo "</tr>"; 

  }
    }
echo "</tbody>";
echo "</table>";
    }
    }

mysqli_close($mysqli);

?> 

1 个答案:

答案 0 :(得分:0)

如果我理解你想要什么,这样就可以了:

if($result) {
    $row1html = "<tr>";
    $row2html = "<tr>";
    while($row = mysqli_fetch_assoc($result)) {
      $row1html .= "<td width='250px' valign='top'>". 
                   $row['luchtvaartmaatschappij'] ."</td>";
      $row2html .= "<td width='50px' valign='top'>". 
                   $row['CountLVMPhotos'] . "</td>";    
    }

    $row1html = "</tr>";
    $row2html = "</tr>";
    echo $row1html . $row2html;
}

可能有更优雅的方式,但这应该有用。

如果你有很多数据,那么这个表格会变得很宽,所以希望你有一个设计。