在数字列表中查找差距

472*_*084 6 php arrays

我有这样一个数组:

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

我想填补空白,看起来像这样:

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
)
Run Code Online (Sandbox Code Playgroud)

如果你看第一个数组的值有1,2,3然后是一个间隙然后是10,11,12,13,14然后是一个间隙然后是23,24,25 ..我怎么能以编程方式找到这些差距并在其位置添加一个新的数组元素

最多会有两个空白.

我想不出一个好方法,做任何想法吗?谢谢.

net*_*der 2

一个简单的for循环,不复制数组,而仅更改原始数组:

$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);
    }
}
Run Code Online (Sandbox Code Playgroud)