获取Timestamp数组中Timestamp位于特定月份的元素


Get elements of Timestamp array where Timestamp is in a specific Month

我有一个时间戳数组(作为键)和字符串数组(作为值)
我想获取数组的所有元素,其中时间戳在特定月份
E.g:2015年4月:自2015年4月1日零时起至2015年4月份30日23:59。

最好的方法是什么?我应该先用ksort对数组进行排序,还是这样会使它变慢?

编辑:我的数组转储:

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

如果更好的话,我也可以很容易地得到这样的数组:

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

将时间戳转换为日期,并与格式化的月份进行比较:

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

在线演示

您也可以使用date函数代替'DateTime

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

还有一种选择:

$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;
    }
}

关于您的问题

我应该先用ksort对数组进行排序,还是这样会使它变慢?

首先对数组进行排序将在数组上进行一次额外的迭代。这意味着是的,它会更慢。虽然里面只有几百件物品,但可能不会有明显的区别。