【问题标题】:php loop with several times per dayphp循环每天几次
【发布时间】:2016-03-09 14:44:48
【问题描述】:

我有一个如下所示的 mysql 表

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

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

<?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');
    }
 ?>

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

 <?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

等等。但是我想要的结果是这样的

Monday 2016-03-10
15:00
16:00
17:00
Tuesday 2016-03-11
15:00
16:00
17:00
18:00

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

【问题讨论】:

  • 你能不能对 $row 数组做一个“print_r”,看看它是如何格式化的?

标签: php html mysqli calendar nested-loops


【解决方案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>";
?>

【讨论】:

    【解决方案2】:

    我刚刚根据你的 mySQL 表结构编辑了最后一个代码 sn -p 未经测试。但我希望你能明白:

    <?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>";
    ?>
    

    编辑

    我只是注意到数据库中的时间来自名为“start_at”的行。修复了代码。

    【讨论】:

      猜你喜欢
      • 2023-02-21
      • 2013-12-31
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 2014-07-06
      • 1970-01-01
      • 2019-01-01
      • 1970-01-01
      相关资源
      最近更新 更多