2015-04-04 201 views
0

我有一个时间戳(作为关键字)和字符串(作为值)的数组。
我想获得数组的所有元素,其中时间戳在特定的月份。
例如:2015年 - 4月:从2015年4月0日零时起至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" ... } 
+1

其中是你的阵列的转储,你试过什么 – Ghost 2015-04-04 10:52:18

回答

3

转换的时间戳的日期和比较反对格式化月:

$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

相反的\DateTime,您还可以使用date功能:

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第一排序我的数组,还是让它变慢?

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

+0

像魔术一样工作!谢谢。 (只需要将'&& $ date-> format('Y')== 2015'添加到'if'。 – Koli 2015-04-04 11:29:04

+0

@Koli也可以做' - > format('Y-m')==='2015- 04'' – Gordon 2015-04-04 11:33:53

+0

或者对于第三个选项:'$ startDate = strtotime('2015年4月的第一天');''和'$ endDate = strtotime('2015年4月23:59:59'的最后一天);' – Koli 2015-04-04 11:53:38