PHP - While循环,按日期分组?

时间:2017-05-07 17:15:55

标签: php html

我在下面循环:

<table>
    <thead>
        <tr>
            <th>Table</th>
        </tr>
    </thead>

$history = $dbh->prepare("SELECT * FROM softbox_bookings ORDER BY time DESC");
$history->execute(); 
while($row = $history->fetch(PDO::FETCH_ASSOC)){

    echo '<tbody>
            <tr>
                <td>'.$row["date"].'</td>
                <td>'.$row["name"].'</td>
            </tr>
            </tbody>';

}
</table>

哪些输出非常简单:

07/05/2017  Name
07/05/2017  Name
29/04/2017  Name

如您所见,上面的输出有两个相同的日期。我的问题是如何将这些日期组合在一起?那么两个第一个相同的日期会显示在一个表格中,最后一个日期会显示在它自己的表格中吗?

像这样:

table 1:
07/05/2017  Name
07/05/2017  Name

table 2:
29/04/2017  Name

这是否可行,使用while循环?

2 个答案:

答案 0 :(得分:1)

在此示例中,每次更改日期时都会打开一个新表

$tableOpened = false;
$lastDate = null;
$history = $dbh->prepare("SELECT * FROM softbox_bookings ORDER BY time DESC");
$history->execute(); 
while($row = $history->fetch(PDO::FETCH_ASSOC)){

    if ($lastDate !== $row['date']) {
        if ($tableOpened) {
            echo '</tbody></table>';//close previous opened table
        }

        //open new table
        echo '<table>
    <thead>
        <tr>
            <th>Table</th>
        </tr>
    </thead><tbody>';
        $tableOpened = true;
    }

    //table content
    echo '<tr>
                <td>'.$row["date"].'</td>
                <td>'.$row["name"].'</td>
            </tr>
            ';


    $lastDate = $row['date'];
}
echo '</tbody></table>';

答案 1 :(得分:0)

试试这个:

<table>
    <thead>
        <tr>
            <th>Table</th>
        </tr>
    </thead>

$history = $dbh->prepare("SELECT DISTINCT(date) FROM softbox_bookings ORDER BY time DESC");
$history->execute(); 
while($row = $history->fetch(PDO::FETCH_ASSOC)){
    $values = $dbh->prepare("SELECT * FROM softbox_bookings WHERE date=".$row['date']." ORDER BY time DESC")->execute();
    echo '<tbody><tr>';

    while($values = $history->fetch(PDO::FETCH_ASSOC)){
         echo '<td>'.$row["date"].'</td>';
         echo '<td>'.$values["name"].'</td>';

    }
    echo '</tr></tbody>';

}
</table>