当值之间的增量超过 1 时,将具有静态值的元素插入到升序整数的平面数组中
我有一个像这样的数组:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 10
[4] => 11
[5] => 12
[6] => 13
[7] => 14
[8] => 23
[9] => 24
[10] => 25
)
我想填补空白,所以它看起来像这样:
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
。如何以编程方式找到这些间隙并在其位置添加新的数组元素?
最多会有两个间隙。
I have an array like this:
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
)
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?
There will be a maximum of two gaps.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一个简单的 for 循环,不复制数组,而仅更改原始数组:
A simple
for
loop, without copying the array, but only altering the original:我会做这样的事情,未经测试但应该有效:)
Shai
I would do something like this, not tested but should work :)
Shai
我将修改输入数组(如 @netcoder 所做的那样),而不是通过填充新的扩展数组来使内存加倍。
foreach()
不适合与array_splice()
一起使用,因为会在迭代时弄乱索引。为了稳定性,请使用
for()
循环。要最大限度地减少count()
的调用,请仅在循环开始时调用一次,然后仅在必要时增加缓存的计数。由于第一个元素永远没有资格注入新元素,因此从索引
1
开始循环。如果前一个元素的值+1等于当前元素的值,则将该位置的元素注入到原始数组中。注入后,改变
$i
和$count
变量,以便循环执行额外的迭代,但不会访问注入的元素。代码:(演示)
输出:
Rather than doubling the memory by populating a new, extended array, I'll modify the input array (as @netcoder did).
foreach()
is unsuitable to use witharray_splice()
because will foul up the indexes while you iterate.For stability, use a
for()
loop. To minimize calls ofcount()
, only call it once at the start of the loop, then bump the cached count only when necessary.Because the first element will never qualify for the injection of the new element, start the loop at index
1
.If the the previous element's value + 1 is equal to the current element's value, then inject the element at that position into the original array. After the injection, bump the
$i
and$count
variables so that the loop performs an additional iteration, but doesn't bother visiting the injected element.Code: (Demo)
Output: