查找号码列表差距 [英] Find gaps in a list of numbers

查看:97
本文介绍了查找号码列表差距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数组:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 10
    [4] => 11
    [5] => 12
    [6] => 13
    [7] => 14
    [8] => 23
    [9] => 24
    [10] => 25
)

我要填补空白,所以它看起来是这样的:

And i want to fill the gaps so it looks like this:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => xxx
    [4] => 10
    [5] => 11
    [6] => 12
    [7] => 13
    [8] => 14
    [9] => xxx
    [10] => 23
    [11] => 24
    [12] => 25
)

如果你看一下第一个数组的值有1,2,3,然后一个缺口,然后10,11,12,13,14,然后一个缺口,然后23,24,25。如何能我觉得编程这些差距,并在其位置添加一个新的数组元素

If you look at the values of the first array there is 1,2,3 and then a gap and then 10,11,12,13,14 and then a gap and then 23,24,25.. How can I programmatically find these gaps and add a new array element in its place

有最多两个缺口会。

我想不出一个好办法做到这一点,任何想法?谢谢你。

I cant think of a good way to do this, any ideas? Thanks.

推荐答案

一个简单的循环,而不复制该数组,但只有改变原来的:

A simple for loop, without copying the array, but only altering the original:

$repl = 'xxx';

for ($i=1; $i<count($array); $i++) {
    $valueR = $array[$i];
    $valueL = $array[$i-1] === $repl ? $array[$i-2] : $array[$i-1];
    if ($valueR > $valueL + 1) {
        array_splice($array, $i++, 0, $repl);
    }
}

这篇关于查找号码列表差距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆