0

I have an array with the keys as timestamps - the actual keys are unix time, I have just formatted it here for simplicity. How can I filter this array so that it unsets all values and only keep the array between 2013-08-02 00:00:00 and 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).
4

2 回答 2

0

如果数组很小,则使用简单的实现:

<?php 

foreach($inputArray as $key => $value) {

if($key < $lowerTimeBound || $key > $upperTimeBound) {
    unset($inputArray[$key]);
}

}

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

于 2013-11-05T10:08:21.323 回答
0

这是一个稍微复杂的过程。没有用于按键名过滤数组的原生 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));
于 2013-11-05T10:09:39.453 回答