PHP循环每天几次

时间:2016-03-09 14:44:48

标签: php html mysqli calendar nested-loops

我有一个看起来像这样的mysql表

string_with_ascii = "..."
string_no_ascii = string_with_ascii.gsub(/\e\[([;\d]+)?m/, '')

然后我使用以下php代码从现在到3个月之间提取日期和时间信息

id          date                    day
1           2016-03-10 15:00:00     monday
2           2016-03-10 16:00:00     monday
3           2016-03-10 17:00:00     monday
4           2016-03-11 15:00:00     tuesday
5           2016-03-11 16:00:00     tuesday
6           2016-03-11 17:00:00     tuesday
7           2016-03-11 18:00:00     tuesday

然后在我的html体内,我输入了类似这样的内容

<?php 
session_start();
if(isset($_SESSION["userID"])){
    $start=date("Y-m-d H:i:s");
echo $stop= date('Y-m-d H:i:s', strtotime("+3 months", strtotime($start)));
    $result2 = $con->query("select * from event WHERE start_at BETWEEN '".$start."' AND '".$stop."'
ORDER by start_at ASC");
}else{
    header('Location: Login.php');
    }
 ?>

生成以下结果

 <?php
     echo "<table><thead><tr><th>Day</th><th>Time</th></tr></thead>";
// output data of each row
while($row = $result2->fetch_assoc()) {
    echo "<tr><td>".$row["name"]."</td><td> ".date('G:i', strtotime($row["start_at"]))."</td></tr>";
}
echo "</table>";
?>

等等。但我想要的结果就是这个

Day     Time
Monday  15:00
Monday  16:00

关于如何更改代码以获得所需输出的想法?

2 个答案:

答案 0 :(得分:1)

这是你的需要。

<?php
$start=date("Y-m-d H:i:s");
$stop= date('Y-m-d H:i:s', strtotime("+3 months", strtotime($start)));

$result2 = $con->query("select * from event WHERE date BETWEEN '".$start."' AND '".$stop."' ORDER by date ASC");

echo "<table>";
$day = null;
while($row = $result2->fetch_assoc()) {
    if($day != $row['day']){
        $day = $row["day"];
        echo "<tr><td>".ucfirst($row['day'])."</td><td>".date('Y-m-d', strtotime($row["date"]))."</td></tr>";
        echo "<tr><td colspan='2'>".date('G:i', strtotime($row["date"]))."</td></tr>";
    }else{
        echo "<tr><td colspan='2'>".date('G:i', strtotime($row["date"]))."</td></tr>";
    }
}
echo "</table>";
?>

答案 1 :(得分:0)

我刚刚编辑了基于mySQL表结构的最后一个代码片段 未经过测试。但我希望你明白这个想法:

<?php
    $day = null;
    echo "<table><thead><tr><th>--</th><th>--</th></tr></thead>";
    while($row = $result2->fetch_assoc()) {
        if($day != $row["name"]) {
            $day = $row["name"];
            echo "<tr><td>".$row["name"]."</td><td> ".strstr($row["date"], " ", -1)."</td></tr>";
        } else {
            echo "<tr><td>".strstr($row["start_at"], " ")."</td><td></td></tr>";
        }
    }
    echo "</table>";
?>

修改

我只是注意到来自数据库的时间来自名为&#34; start_at&#34;的行。修正了代码。