0

我有下表 -

S.No. (Auto Increment, Primary Key)
Timestamp (Records date in yyyy-mm-dd format)
type (Records the type of document Ex. 1,2,3,etc.)
Number (Records the serial number of a particular type of document)

现在我想生成一个表,我想在其中按时间戳对数据进行排序。基于type我想在报告的左侧和右侧显示一些列。所以,我想订购我的结果集首先按时间戳排序,然后按类型排序。假设我想要左侧的 1、2、3 和右侧的 4、5、6。所以我想要在我的结果集中必须有左右交替的行。前任。

Timestamp                     Type 
2012-01-01                      1
2012-01-01                      4
2012-01-01                      1
2012-01-01                      4
2012-01-01                      1
2012-01-01                      5
2012-01-01                      1
2012-01-01                      6
2012-01-01                      2
2012-01-01                      2
2012-01-01                      2

我试图这样做,但没有得到想要的结果。这是我想要的最终结果——

时间戳类型 时间戳类型
2012-01-01 1 2012-01-01 4
2012-01-01 1 2012-01-01 4
2012-01-01 1
2012-01-02 2 2012-01-02 6
2012-01- 02 2 2012-01-02 6
                                        2012-01-03 5
                                         2012-01-03 5
                                        2012-01-03 5

4

2 回答 2

1

如果您只是在遍历结果集时将PHP 生成的所有 HTML 代码收集在两个变量 ( $leftHtml, )中,则不需要排序。$rightHtml

完成后,您可以一次性将整个 html 回显到正确的位置。那么,如何对行进行排序并不重要(例如,只要您不希望它们按时间排序)。

注意:“时间戳”和“类型”作为列名从长远来看会导致错误,因为这些是保留字。

伪代码:

$left = "";
$right = "";
foreach ( $result as $row )
{
  if ( $row['type'] == '1' )
       $left .= "<p>left: " . $row['timestamp'];

  if ( $row['type'] == '2' )
       $right.= "<p>right: " . $row['timestamp'];
}

echo "<table><tr><td>" . $left . "</td><td>" . $right. "</td></tr></table>";
于 2013-06-30T15:02:39.453 回答
0

如果你愿意,你可以像这样进行查询。它的作用是说如果类型是 1、2 或 3,则 Side = 1(左),否则 Side = 2(右)。

SELECT 
    `S.No.`, `Timestamp`, `Type`, `Number`, 
    IF(`Type` IN (1,2,3), 1, 2) as `Side`
FROM `Table`
ORDER BY `Side`, `Timestamp`, `Type`

由于我们已按 Side 订购,因此我们可以这样做:

<?php
$leftSide = true;
echo '<div class="left-side">';
while ($row = mysqli_fetch_assoc($result)) {
    if ($leftSide && $row['Side'] == 2) {
        // We've hit our first right side row so close the left side div and 
        // start theright side div
        echo '</div><div class="right-side">';
        $leftSide = false;
    }

    // Do something with the row data here
}
echo '</div>';
于 2013-06-30T15:10:00.427 回答