php - 如何在 PHP 中检查当前时间和数据库时间是否相等
问题描述
我正在尝试比较 2 次PHP
。我从记事本中获取并存储时间Mysql
,例如
- 21:30
- 22:00
- 22:30
然后我从中读取时间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
}
请注意,这两种类型都只是字符串,并且尝试使用===
仍然没有用处进行比较。
解决方案
但是,您所做的事情并不是最佳实践,但是您在将数组与字符串进行比较时犯了一个错误:
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
}
}
注意
顺便说一句,最好将两个变量与===
运算符进行比较,因为它将检查它们的类型
推荐阅读
- java - 如何根据标题从RecyclerView打开一个项目到另一个项目 - MYSQL数据库
- python - 分组时获取两列字典列表
- python - 如何获得任意数的除数
- mysql - 如何有效地将动态文本保存到数据库中?
- rust - 返回实现多个特征的对象 - 装饰器模式
- angular - 将数据从组件传递到 Angular 2 中的模块
- sql - 如何在 CLOB 字段的第 10 位进行 regex_replace
- python - Getting URL as a parameter in Flask - but Flask stripping out the params from the URL
- css - 卡片使用 MaterializeCSS 和 VUE 跳过行
- java - IntelliJ IDEA 在调试时卡在“收集数据”