开发者

accessing value of next() and rewind() in a PHP iterator run in a foreach loop

Saw this in wikipedia, this is what happens when you traverse an iterator via a foreach loop:

These methods are all being used in a complete foreach( $object as $key=>$value ) sequence. The methods are executed in the following order:

rewind() 
while valid() {
    current() in $value 
    key() in $key 
    next()
} 
End of Loop

I was wondering how I ca开发者_运维知识库n access the values of next() and rewind(). Any ideas?

UPDATE: Access them from inside the foreach loop


What do you think about it?

for ($i =0; $i < count($arr); $i++) {

    $last = ($i == 0) ? null : $arr[$i-1];
    $next = (isset($arr[$i+1]) ? $arr[$i+1] : null;
    $current = $arr[$i];

    //...

}


You can't. To trigger a reset, you'd need to reenter the loop, and to call next, you need to go into the next iteration.

So the closest (PHP 5.3) would be this:

label:
foreach ($var as $k => $v) {

    /* ... */
    goto label; //re-enter loop

    /* ... */
    continue; //force going to the next iteration

    /* ... */
}

If you are using iterators directly, you can use those calls:

$r = 0; $s = 0;
$it = new ArrayIterator(array("a" => 3, "b" => 5, "c" => 7));
foreach ($it as $k => $v) {
    echo "$k => $v\n";
    if ($s == 0) {
        $s = 1;
        $it->next(); //jump over one iteration
    } else if ($r == 0) {
        $r = 1;
        $it->rewind();
    }
}

gives:

a => 3
c => 7
b => 5
c => 7


IF its implementing the Iterator interface you can call those method yourself but they have implications.

rewind and next both set the position of the pointer in the dataset being iterated over... they dont actually return the element or index. So calling either of these is going to screw up your loop.

current will return the same variable you already have in the loop - ie. the element for the current iteration. key will return the index for that item in the set.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜