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

Php 当键是时间戳时,筛选范围内的数组,php,arrays,function,Php,Arrays,Function,我有一个以键作为时间戳的数组-实际的键是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 ---->&g

我有一个以键作为时间戳的数组-实际的键是unix时间,为了简单起见,我刚刚在这里格式化了它。如何筛选此数组,使其取消设置所有值,并仅将数组保持在2013-08-02 00:00:002013-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函数用于按键名过滤数组<代码>数组\过滤器
仅按键值过滤

所以你需要这样的东西:

$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));
$calls=array(…);//你的阵列
//获取作为数组值的时间
$times=数组翻转(数组翻转键($calls));
$bounders=数组(
“开始”=>新的日期时间('2013-08-02 00:00:00'),
'结束'=>新日期时间('2013-08-02 00:02:00'),
);
//此函数用于过滤时间
//超出$边界的时间将从数组中删除
$times=array_filter($times,function($val)use($bounders){
$time=新日期时间($val);
如果($time<$bounders['start'])| |($time>$bounders['end'])){
返回false;
}否则{
返回true;
}
});
//仅保留$calls中键在$times数组中的元素
$calls=array_intersect($calls,array_flip($times));

阵列的典型大小是多少?您是否总是在两个unix时间戳之间进行筛选,这两个时间戳肯定作为密钥存在于阵列中?或者数组中是否可能缺少起点和终点(并且需要过滤它们之间的所有点)?大小为几千个元素。我将始终筛选数组中肯定存在的unix时间戳。