如何从外部访问foreach中的数组?

我的记录表中有StartTime和EndTime列,它们包含时间数据,我试图检查输入上写入的时间是否在StartTime和之间EndTime。


在 Records 表中,一条记录的StartTime: 09:00和EndTime: 12:00以及它们的周期为10:00 , 11:00


因此,如果在输入中写入 10:00,PHP 必须回显:“这个小时已经存在!”


同时,我不仅检查表中某一行的时间,还检查其他记录行的时间。我使用whileandforeach循环执行此操作,但我找不到如何if正确检查语句中的结果数组,因此我的if语句不起作用。如何准确检查我在循环中创建的周期foreach?


PHP


<?php

    

    $stmt1 = $db->query('SELECT StartTime, EndTime FROM records');

    

    $periods[] = "";

    while($row = $stmt1->fetch()){


        echo '<li>'.$row['StartTime'].' - '.$row['EndTime'].'</li>';


        $start = new DateTime($row['StartTime']);

        $interval = new DateInterval('PT1H');

        $end = new DateTime($row['EndTime']);       

        

        $period = new DatePeriod($start, $interval, $end, DatePeriod::EXCLUDE_START_DATE);


        foreach ($period as $date) {

            $periods[] = $date->format('H:i');  

        }                   

    }               


    echo "<br>";

    

    if(isset($_POST['submit'])){

        

        //Date validations

        $inputTime = new DateTime($_POST['inputTime']);


        if ($inputTime == $periods) {

            echo "This hour already exists!";

        }                       

                                    

    }


?>

HTML 表单


<form action="index.php" method="post">

    <p>Time</p>

    <input type="text" id="inputTime" name="inputTime">

    <br>    

    <input type="submit" name="submit" value="Check">

</form> 


繁星coding
浏览 104回答 1
1回答

米琪卡哇伊

我会使用简单的时间戳,而不是DateTime对象。$stmt1 = $db->query('SELECT StartTime, EndTime FROM records');$periods = [];while ($row = $stmt1->fetch()){&nbsp; &nbsp; echo '<li>'.$row['StartTime'].' - '.$row['EndTime'].'</li>';&nbsp; &nbsp; $periods[] = [strtotime($row['StartTime']), strtotime($row['EndTime'])];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;echo "<br>";if (isset($_POST['submit'])){&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; //Date validations&nbsp; &nbsp; $inputTime = strtotime($_POST['inputTime']);&nbsp; &nbsp; $exists = false;&nbsp; &nbsp; foreach ($periods as $period) {&nbsp; &nbsp; &nbsp; &nbsp; if ($inputTime >= $period[0] && $inputTime <= $period[1]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $exists = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if ($exists) {&nbsp; &nbsp; &nbsp; &nbsp; echo "This hour already exists!";&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP