When unsetting elements as you go it will not remove the second index of the Array being worked on. Im not sure exactly why but there is some speculations that when calling unsetOffset(); it resets the pointer aswell.
<?php
$a = new ArrayObject( range( 0,9 ) );
$b = new ArrayIterator( $a );
for ( $b->rewind(); $b->valid(); $b->next() )
{
echo "#{$b->key()} - {$b->current()} - \r\n";
$b->offsetUnset( $b->key() );
}
?>
To avoid this bug you can call offsetUnset in the for loop
<?php
/*** ... ***/
for ( $b->rewind(); $b->valid(); $b->offsetUnset( $b->key() ) )
{
/*** ... ***/
?>
Or unset it directly in the ArrayObject
<?php
/*** ... ***/
$a->offsetUnset( $b->key() );
/*** ... ***/
?>
which will produce correct resultsArrayIterator::offsetUnset
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
ArrayIterator::offsetUnset
Референца за `arrayiterator.offsetunset.php` со подобрена типографија и навигација.
ArrayIterator::offsetUnset
класата mysqli_driver
ArrayIterator::offsetUnset — Отстрани вредност за поместување
= NULL
Отстранува вредност за поместување.
Ако итерацијата е во тек, и ArrayIterator::offsetUnset() се користи за отстранување на тековниот индекс на итерација, позицијата на итерација ќе се помести на следниот индекс. Бидејќи позицијата на итерација исто така се поместува на крајот на
foreach телото на циклусот, употребата на
ArrayIterator::offsetUnset() внатре во
foreach циклусот може да резултира со прескокнување на индексите.
Параметри
key-
Поместувањето за отстранување.
Вратени вредности
Не се враќа вредност.
Види Исто така
- ArrayIterator::offsetGet() - Провери дали офсетот постои
- ArrayIterator::offsetSet() - Постави вредност за поместување
Белешки од корисници 3 белешки
This is my solution for problem with offsetUnset
<?php
$a = new ArrayObject( range( 0,9 ) );
$b = new ArrayIterator( $a );
for ( $b->rewind(); $b->valid(); )
{
echo "#{$b->key()} - {$b->current()} - <br>\r\n";
if($b->key()==0 || $b->key()==1){
$b->offsetUnset( $b->key() );
}else {
$b->next();
}
}
var_dump($b);
?>Make sure you use this function to unset a value. You can't access this iterator's values as an array. Ex:
<?php
$iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arr));
foreach($iterator as $key => $value)
{
unset($iterator[$key]);
}
?>
Will return :
PHP Fatal error: Cannot use object of type RecursiveIteratorIterator as array
offsetUnset works properly even when removing items from nested arrays.