如何找到在PHP序列缺失值? [英] How to find missing values in a sequence with PHP?
问题描述
假设你有一个数组值=>时间戳。值被增加与时间,但它们可被复位,在任何时刻。
Suppose you have an array "value => timestamp". The values are increasing with the time but they can be reset at any moment.
例如:
$array = array(
1 => 6000,
2 => 7000,
3 => 8000,
7 => 9000,
8 => 10000,
9 => 11000,
55 => 1000,
56 => 2000,
57 => 3000,
59 => 4000,
60 => 5000,
);
我想检索所有的缺失值此数组。
I would like to retrieve all the missing values from this array.
这个例子将返回:
array(4,5,6,58)
我不希望所有值55 9至因为9比另一个更高的值更新的。
I don't want all the values between 9 and 55 because 9 is newer than the other higher values.
在实际条件下的脚本会处理上千个值,因此必须是有效的。
In real condition the script will deal with thousands of values so it need to be efficient.
感谢您的帮助!
更新: 最初的阵列可通过时间戳进行排序,如果是比较容易的算法。
UPDATE : The initial array can be ordered by timestamps if it is easier for the algorithm.
更新2: 在我的例子中的值是UNIX时间戳,使他们看起来更像是这样:1285242603,但为便于阅读,我之所以简化IT
UPDATE 2 : In my example the values are UNIX timestamps so they would look more like this : 1285242603 but for readability reason I simplified it.
推荐答案
下面是另一种解决办法:
Here’s another solution:
$prev = null;
$missing = array();
foreach ($array as $curr => $value) {
if (!is_null($prev)) {
if ($curr > $prev+1 && $value > $array[$prev]) {
$missing = array_merge($missing, range($prev+1, $curr-1));
}
}
$prev = $curr;
}
这篇关于如何找到在PHP序列缺失值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!