首页 > 解决方案 > 如何在 PHP 中检查当前时间和数据库时间是否相等

问题描述

我正在尝试比较 2 次PHP。我从记事本中获取并存储时间Mysql,例如

然后我从中读取时间file并将其存储在array.Below 是我的代码

$myfile = file('Scheduled_data.txt');
$time_array = array();

// store into array 
foreach ($myfile as $line) {
    $line_array = explode("\t", $line);
    $time_array[] =  $line_array[0];
}

//looping array 
for ($i = 0; $i < count($time_array); $i++) {
    $timezone = new DateTime("now", new DateTimeZone('Asia/Kolkata') );
    $current_time=$timezone->format('H:i');
    echo  $time_array[$i]; //ex: first data 21:30
    echo "\t";
    echo $current_time; // 21:30
    if($time_array == $current_time)
    { 
      echo "yes"; // not moving inside if cond
    }
}

我无法在里面移动If condition。但我可以在打印时间时看到相同的时间。

更新:对不起,我只做了这个,但仍然没有进入If状态

if($time_array[$i] == $current_time)
        { 
          echo "yes"; // not moving inside if cond
        }

请注意,这两种类型都只是字符串,并且尝试使用===仍然没有用处进行比较。

标签: phpdatetimeif-statementtimezone

解决方案


但是,您所做的事情并不是最佳实践,但是您在将数组与字符串进行比较时犯了一个错误:

if($time_array == $current_time)
{ 
  echo "yes"; // not moving inside if cond
}

解决方案

你需要像这样检查th$i索引:$time_array$current_time

if(strtotime($time_array[$i]) == strtotime($current_time))
{ 
  echo "yes"; // not moving inside if cond
}

所以:

最好使用strtotime() php函数进行比较:

$myfile = file('Scheduled_data.txt');
$time_array = array();

// store into array
foreach ($myfile as $line) {
    $line_array = explode("\t", $line);
    $time_array[] =  $line_array[0];
}

//looping array
for ($i = 0; $i < count($time_array); $i++) {
    $timezone = new DateTime("now", new DateTimeZone('Asia/Kolkata') );
    $current_time=$timezone->format('H:i');
    echo  $time_array[$i]; //ex: first data 21:30
    echo "\n\r";
    echo $current_time; // 21:30
    if(strtotime($time_array[$i]) == strtotime($current_time)){ 
        echo "yes"; // not moving inside if cond
    }
}

注意

顺便说一句,最好将两个变量与===运算符进行比较,因为它将检查它们的类型


推荐阅读