计算具有指定值的行

时间:2019-11-16 07:09:58

标签: php

我有一个包含以下内容的文件(txt):

user1 2019-11-14 10:48:01
user2 2019-11-10 11:38:25
user3 2019-11-15 09:45:30
user4 2019-11-12 00:15:01
user5 2019-11-15 00:15:01

我要计算服务器时间之前24小时的行。 不幸的是,我没有使用以下代码成功。您有更好的解决方案吗?

<?php
$lines = file('user.txt');

foreach($lines as $line) {
        $section = explode(" ", $line);
        $lasttime = "$section[1]"." "."$section[2]";
        $timetosecend = strtotime(date("Y-m-d H:i:s"));
        $lasttimetosecend = strtotime($lasttime);
        $count = 0;
        $countitem = $timetosecend-$lasttimetosecend<86400;

        if (strstr($line, $countitem)) {
            if (($timetosecend-$lasttimetosecend)>86400) {
            $count++;
        }
    }
}
echo $count;
?>

2 个答案:

答案 0 :(得分:2)

您可以使用explodelimit参数来简化代码,从而避免将$lasttime重新组合在一起,并且只计算一次当前时间。正如@NigelRen所指出的,我们可以计算一天前的时间,然后只需要检查$timetosecond - $lasttimetosecond的符号,这会更有效:

$timetosecond = strtotime("now") - 86400;
$count = 0;
foreach($lines as $line) {
    list(, $lasttime) = explode(" ", $line, 2);
    $lasttimetosecond = strtotime($lasttime);
    if ($timetosecond - $lasttimetosecond < 0) {
        $count++;
    }
}
echo $count;

Demo on 3v4l.org

答案 1 :(得分:1)

最后尝试删除。
您还需要从foreach中声明$count,因为每次循环时都将count重写为0。

<?php
$lines = file('user.txt');
$count = 0; //  <-------------- here

foreach($lines as $line) {
        $section = explode(" ", $line);
        $lasttime = "$section[1]"." "."$section[2]";
        $timetosecend = strtotime(date("Y-m-d H:i:s"));
        $lasttimetosecend = strtotime($lasttime); 
        $countitem = $timetosecend-$lasttimetosecend<86400;

        if ($countitem) {  // <---------- here
            $count++;
        }
    }
echo $count;