文字

ArrayIterator::offsetUnset

(PHP 5 >= 5.0.0)

ArrayIterator::offsetUnsetUnset value for an offset

说明

public void ArrayIterator::offsetUnset ( string $index )

Unsets a value for an offset.

Warning

本函数还未编写文档,仅有参数列表。

参数

index

The offset to unset.

返回值

没有返回值。

参见

  • ArrayIterator::offsetGet() - Get value for an offset
  • ArrayIterator::offsetSet() - Set value for an offset

用户评论:

[#1] rkos... [2014-02-14 09:11:59]

This is my solution for problem with offsetUnset
<?php

$a 
= new ArrayObjectrange0,) );
$b = new ArrayIterator$a );

for ( 
$b->rewind(); $b->valid();  )
{
    echo 
"#{$b->key()} - {$b->current()} - <br>\r\n";
    if(
$b->key()==|| $b->key()==1){
        
$b->offsetUnset$b->key() );
    }else {
        
$b->next();
    }
}

var_dump($b);
?>

[#2] olav at fwt dot no [2011-07-07 04:12:30]

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 ArrayObjectrange0,) );
$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 results

[#3] Adil Baig @ AIdezigns [2011-06-23 23:23:30]

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.

上一篇: 下一篇: