duanrenchuo9244 2019-04-04 22: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-04 23: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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部