假设代理存储在多维数组中,结构如下:
[Agent - 167] => Array
(
[0] => Array
(
[0] => 2015-07-17 00:01:51.417080
[1] => Agent - 167
[2] => LOGIN
)
[1] => Array
(
[0] => 2015-07-17 00:02:28.821206
[1] => Agent - 167
[2] => LOGOUT
)
[2] => Array
(
[0] => 2015-07-17 00:02:37.257944
[1] => Agent - 167
[2] => LOGIN
)
[3] => Array
(
[0] => 2015-07-21 07:16:51.457435
[1] => Agent - 167
[2] => LOGIN
)
[4] => Array
(
[0] => 2015-07-21 07:20:51.016638
[1] => Agent - 167
[2] => LOGOUT
)
)
我想计算每个代理的每个Login
和Logout
事件之间的时间差,并得到聚合。这是足够直接的,因为时间日志是在内部数组的第一个元素,所以[0][0] = Time
。事件发生在第三元素上。只有当下面的事件是LOGOUT
,前面的事件是LOGIN
时,我的计算才有效。
然而,有时代理超时而不是注销连续记录两个LOGIN
事件,我想跳过具有LOGIN
事件的数组如果下一个数组也具有LOGIN
事件并继续我的计算。
我使用下面的代码来执行我的计算:
foreach ($pse_array as $value) {
$total = 0;
for ($i = 0; $i < count($value); $i+=2) {
$srtTime = strtotime($value[$i][0]);
$endTime = strtotime($value[$i + 1][0]);
$interval = $endTime - $srtTime;
$total += $interval;
}
echo gmdate("H:i:s", $total) . " Minutes <br>";
}
我也知道,我可以进行比较,以检查事件是否符合我的标准与If statement
,但我不确定我将如何跳过数组。
$timeout = strtotime('00:30') - strtotime('00:00');
foreach ($pse_array as $value) { // loop by user
$total = 0;
$login = false; // time of login
foreach ($value as $item) { // loop by entry
if ($item[2] == 'LOGIN') {
//if ($login) $total += $timeout; // two login successively
// you can remove this
$login = $item[0]; // save login time
continue;
}
$srtTime = strtotime($login); // if here, status = LOGOUT
$login = false; // mark that previos was logout
$endTime = strtotime($item[0]); // further your code
$interval = $endTime - $srtTime;
$total += $interval; // You receive interval in sec
}
echo $total/60 . " Minutes <br>";
}
经过几次尝试,终于找到了一个快速简单的解决方案
$pse_array = [ 'Agent - 167' => [
[ 0 => '2015-07-17 00:01:51.417080',
1 => 'Agent - 167',
2 => 'LOGIN'
],
[
0 => '2015-07-17 00:02:28.821206',
1 => 'Agent - 167',
2 => 'LOGOUT'
],
[
0 => '2015-07-17 00:02:37.257944',
1 => 'Agent - 167',
2 => 'LOGIN'
],
[
0 => '2015-07-21 07:16:51.457435',
1 => 'Agent - 167',
2 => 'LOGIN'
],
[
0 => '2015-07-21 07:20:51.016638',
1 => 'Agent - 167',
2 => 'LOGOUT'
]
]
];
foreach ($pse_array as $value) {
$total = 0;
for ($i = 0; $i < count($value);
) /* $i+=2) */ {
if ($value[$i][2] === "LOGIN" && $value[$i + 1][2] === "LOGIN") {
$i+=1;
} else {
$srtTime = strtotime($value[$i][0]);
$endTime = strtotime($value[$i + 1][0]);
$interval = $endTime - $srtTime;
$total += $interval;
$i+=2;
}
}
echo gmdate("H:i:s", $total) . " Minutes <br>";
}
工作目录:https://eval.in/406539