当键为时间戳时,筛选范围内的数组


Filter an array within a range when keys are timestamps

我有一个数组,其中键作为时间戳 - 实际键是 unix 时间,为了简单起见,我只是在这里格式化了它。如何过滤此数组,使其取消设置所有值,仅将数组保留在 2013-08-02 00:00:00 和 2013-08-02 00:02:00 之间?

2013-08-01 23:58:30 ---->> 322 active call(s).
2013-08-01 23:58:45 ---->> 322 active call(s).
2013-08-01 23:59:00 ---->> 324 active call(s).
2013-08-01 23:59:15 ---->> 324 active call(s).
2013-08-01 23:59:30 ---->> 327 active call(s).
2013-08-01 23:59:45 ---->> 330 active call(s).
2013-08-02 00:00:00 ---->> 336 active call(s).
2013-08-02 00:00:15 ---->> 343 active call(s).
2013-08-02 00:00:30 ---->> 342 active call(s).
2013-08-02 00:00:45 ---->> 342 active call(s).
2013-08-02 00:01:00 ---->> 335 active call(s).
2013-08-02 00:01:15 ---->> 325 active call(s).
2013-08-02 00:01:30 ---->> 324 active call(s).
2013-08-02 00:01:45 ---->> 322 active call(s).
2013-08-02 00:02:00 ---->> 322 active call(s).
2013-08-02 00:02:15 ---->> 319 active call(s).
2013-08-02 00:02:30 ---->> 317 active call(s).
2013-08-02 00:02:45 ---->> 313 active call(s).

如果数组很小,则使用朴素的实现:

<?php 
foreach($inputArray as $key => $value) {
if($key < $lowerTimeBound || $key > $upperTimeBound) {
    unset($inputArray[$key]);
}
}

这对于大量实体来说效率不高。

这是一个稍微复杂的过程。没有用于按键名过滤数组的本机 PHP 函数。 array_filter仅按键值进行筛选。

所以你需要这样的东西:

$calls = array(...); // your array
// get the times as the values of an array
$times = array_flip(array_keys($calls));
$boundaries = array(
    'start' => new DateTime('2013-08-02 00:00:00'),
    'end' => new DateTime('2013-08-02 00:02:00'),
);
// this function filters the times
// times outside the $boundaries will be removed from the array
$times = array_filter($times, function($val) use ($boundaries) {
    $time = new DateTime($val);
    if (($time < $boundaries['start']) || ($time > $boundaries['end'])) {
        return false;
    } else {
        return true;
    }
});
// keep only the elements in $calls whose keys are in the $times array
$calls = array_intersect($calls, array_flip($times));