Php, Spl, ArrayIterator

醉酒当歌 提交于 2019-12-11 06:38:14

问题


I am trying to understand piece of code:

$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 />";
}

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:

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.

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.


回答1:


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";
}

Output:

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

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...




回答2:


Here is a use of offsetUnset where elements are unset by their index and giving the expected result :

$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');

$object = new \ArrayIterator($array);

foreach ($object->getArrayCopy() as $i => $item) {
    if($item === 'kiwi') {
        $object->offsetUnset( $i );
    }
}

print_r($object->getArrayCopy());

Output:

Array ( [0] => koala [1] => kangaroo [2] => wombat [3] => wallaby [4] => emu [6] => kookaburra [7] => platypus )


来源:https://stackoverflow.com/questions/12409990/php-spl-arrayiterator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!