我有数组数组: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 ([0] => 16 [1] => 17)
阵列温度是不正常
Array ([0] => 18 [1] => 18 [2] => 18)
它应该是18,18,19
这种情况如何解决? 谢谢。
我之前解决过,所以我不得不刷新我的记忆。 – phpJs 2012-09-25 00:21:56