douze1332 2015-04-04 10:41
浏览 126
已采纳

获取Timestamp数组的元素,其中Timestamp在特定月份中

I have an Array of Timestamps (as key) and Strings (as value).
I would like to get all the elements of the Array, where the Timestamp is in a specific Month.
E.g: 2015-April: from 0:00 1th of April 2015, until 23:59 30th of April 2015.

What is the best method for that? Shall i sort my array first with ksort, or that makes it slower?

EDITED: Dump of my array:

array(327) { [1428226200]=> string(95) "foo" [1428231600]=> string(95) "bar" ... } 

I also can get an array like this easily, if it's better:

array(327) { ["2014/03/05 09:30"]=> string(95) "foo" ["2015/04/07 11:00"]=> string(95) "bar" ... }
  • 写回答

1条回答 默认 最新

  • dongping5230 2015-04-04 11:03
    关注

    Convert the timestamps to a date and compare against the formatted month:

    $dates = /* your array */
    $aprilDates = [];
    foreach ($dates as $timestamp => $value) {
        $date = new \DateTime("@$timestamp");
        if ($date instanceof \DateTime && $date->format('m') == 4) {
            $aprilDates[$timestamp] = $value;
        }
    }
    

    Online Demo

    Instead of \DateTime, you can also use the date function:

    foreach ($dates as $timestamp => $value) {
        if (date('m', $timestamp) == 2) {
            $aprilDates[$timestamp] = $value;
        }
    }
    

    Yet another option:

    $startDate = strtotime('first day of April');
    $endDate = strtotime('last day of April 23:59:59');
    
    foreach ($dates as $timestamp => $value) {
        if ($timestamp >= $startDate && $timestamp <= $endDate) {
            echo $value, PHP_EOL;
        }
    }
    

    Regarding your question

    Shall i sort my array first with ksort, or that makes it slower?

    Sorting the array first will do one additional iteration over the array. That means yes, it will be slower. With only a few hundreds items in there, it will likely make no noticeable difference though.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 急,ubuntu安装后no caching mode page found等
  • ¥15 联想交换机NE2580O/NE1064TO安装SONIC
  • ¥15 防火墙的混合模式配置
  • ¥15 Ubuntu不小心注销了要怎么恢复啊
  • ¥15 win10电脑安装完plcsim advanced4.0运行时为什么会提示找不到虚拟网卡
  • ¥15 安装powerbuilder10卡在安装程序正在运行这个页面 没有下一步任何指令
  • ¥15 关于mpi的问题:请问遇到这种情况需要怎么解决,出现这个问题后电脑不能进行mpi多核运行只能进行单核运行
  • ¥50 微信聊天记录备份到电脑提示成功了,但还是没同步到电脑微信
  • ¥15 python怎么在已有视频文件后添加新帧
  • ¥20 虚幻UE引擎如何让多个同一个蓝图的NPC执行一样的动画,