问题
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