PHP,SPL,ArrayIterator [英] Php, Spl, ArrayIterator

查看:121
本文介绍了PHP,SPL,ArrayIterator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解一段代码:

$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');
$object = new ArrayIterator($array);
foreach($object as $key=>$value)
{
if($object->offSetGet($key) === 'kiwi')
{
$object->offSetUnset($key);
}
echo $key.' - '.$value."<br />";
}

我试图理解的是为什么 offSetUnset 将指针指向数组中第二个元素而不是第一个元素,我的理论是以下事件序列:

What i was trying to understand is why offSetUnset is taking the pointer to the second element at the array and not to the first one, My theory is the following sequence of events:

当将offSetUnset称为指向元素0的指针goe时, offSetUnset等到foreach请求一个元素,然后offSetUnset 知道它可以起作用,所以,当它发生时,它删除了先前给定的元素,当它完成迭代时,它转到了下一个元素,这就是为什么我认为我们在offSetUnset重置foreach循环之后丢失了0元素.

When the offSetUnset is called the pointer goe's to element 0, The offSetUnset wait until the foreach asking for an element then the offSetUnset knows it can act, So when it's happen's it removes the element given earlier, When it's finish the iteration it goe's to the next element and thats why i think we losing the 0 element after the offSetUnset reset the foreach loop.

但是正如我所说的,这是我在问到这里之前提出的唯一理论,因此,如果有人可以请我完成事件序列,那么我们就失去了0元素,谢谢大家,祝您愉快.

But as i sayed its only a theory i came up with before asking here, so if some one can take me please through the event sequence made us losing the 0 element, Thank you all and have a nice day.

推荐答案

有一个记载错误,听起来与您发现的错误非常接近"!
为了解决该问题,您可以执行以下操作:

There is a documented bug which sounds very "close" to the bug you've found!
In order to work-around it, you can do as follows:

$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');
$object = new ArrayIterator($array);
for ( $object->rewind(); $object->valid(); $object->next() )
{
    if($object->current() === 'kiwi')
    {
        $object->offsetUnset( $object->key() );
    }
    echo $object->key().' - '.$object->offsetGet($object->key())."\n";
}

输出:

0 - koala
1 - kangaroo
2 - wombat
3 - wallaby
4 - emu
0 - koala  (this time it starts over from the first element!)
1 - kangaroo
2 - wombat
3 - wallaby
4 - emu
6 - kookaburra
7 - platypus

如果需要,您可以提交错误,但根据我在ArrayIterator中看到的有关bug的其他线程-我很难相信它将很快得到修复...

If you want, you can submit a bug, but according to the other threads I saw about bugs in ArrayIterator - I find it hard to believe it will be fixed any time soon...

这篇关于PHP,SPL,ArrayIterator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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