我有数字数组:16,17,19,19,20。我需要找到一个缺失的数字/间隙(在这种情况下,它是 18/一个数字,但它可能是两个数字,例如 16、17、20、21),然后我想以阵列其余部分的方式填补空白向上移动一 (x) 个数字。这个数组可以有更多的缺失数字(间隙),例如 16、17、19、19、20、21、23、23。我有这个循环,但有问题 - 见评论:
<?php
$ar = array(16,17,19,19,20);
$action = false;
$new = array();
$temp = array();
foreach ( $ar as $k => $v ) {
if ( $k == 0 )
{
// case 0 - insert first value of var into array - never need to change
$new[] = $v;
}
elseif ( $k > 0 )
{
if ( end($new) + 1 == $v )
{
// case 1 - numbers are consequence/no gap - insert into array - no change
$new[] = $v;
}
elseif ( end($new) + 1 != $v )
{
// case 2 - there is a gap: find the size of the gap (1,2,x) and then subtract all next values of array with the gap
$gap = $v - end($new) - 1 ; // find value of the gap
//echo "<br> gap is: " . $gap; // PROBLEM - gap get increased by every loop but i need to keep gap size static and process rest of the array
$action = true;
if ( $action = true )
{
$temp[] = $v - $gap;
}
}
}
}
echo "<br>";
print_r ( $new );
echo "<br>";
print_r ( $temp );
所以结果是:array new 没问题
Array ( [0] => 16 [1] => 17 )
数组温度不正常
Array ( [0] => 18 [1] => 18 [2] => 18 )
应该是 18,18,19
这种情况如何解决?谢谢。