我有一个数组,其中的键作为时间戳 - 实际的键是unix时间,为了简单起见,我刚刚将其格式化。如何过滤此数组以使其取消设置所有值并仅将数组保持在 2013-08-02 00:00:00 和 2013-08-02 00:02:00 <之间/ strong>?
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).
答案 0 :(得分:0)
如果数组很小,那么使用一个简单的实现:
<?php
foreach($inputArray as $key => $value) {
if($key < $lowerTimeBound || $key > $upperTimeBound) {
unset($inputArray[$key]);
}
}
这对大量实体来说效率不高。
答案 1 :(得分: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));