duanrenchuo9244 2019-04-05 06:20
浏览 96
已采纳

如何筛选对象数组并检查最新的时间戳

I want to create a restriction after a action for different id's, so I decided to store the entry time and id of the post into the session variable. Then I can fetch the recent timestamp and disallow the user to do that action to id for 5 minutes to stop spamming of queries

$vars = (object) array("idpost" => $idpost,"time" => time());
$_SESSION['ids'][] = $vars;

And if the count of the array is more than 5, then stop the execution of script. But after 5 min, proceed the script.

$neededObject = array_filter( //filtering the array for a specific idpost
    $_SESSION['ids'],
    function ($e) use ($idpost) {
        return $e->idpost === $idpost;
    }
);
if (count($neededObject) > 5){// user has used id it many times
   $timestamps = array_filter(
    $neededObject,
    function ($e) use ($idpost) {
        return $e->timestamp // do something here to check the recent timestamps from all others;
    }
}

I can't find a way to compare the most recent time stamp and check that if 5 mins have passed. How can I fetch the most recent timestamp and check that 5 minutes have passed? I can do this if i get the most recent timestamp from the array.

if (time() - $mostrecenttimestampfromarray < 5*60*60 ) // 5 mins have passed
  • 写回答

1条回答 默认 最新

  • dongxun6690 2019-04-05 07:03
    关注

    I'm not sure what you're trying to achieve by using array_filter, is that necessary?

    Can you loop through the neededObjects to find the latest timestamp and then check it. Something like this:

    if ( count( $neededObject ) > 5 ) {
    
        $latestTimestamp = 0;
    
        foreach ( $neededObject as $object ) {
    
            if ( $object->time > $latestTimestamp ) {
                $latestTimestamp = $object->time;
            }       
        }
    
        if ( time() < $latestTimestamp + 5*60 ) {
            return;
        }   
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog