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 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥15 看一下OPENMV原理图有没有错误
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 vite打包后,页面出现h.createElement is not a function,但本地运行正常
  • ¥15 Java,消息推送配置
  • ¥15 Java计划序号重编制功能,此功能会对所有序号重新排序,排序后不改变前后置关系。
  • ¥15 关于哈夫曼树应用得到一些问题