$animals = array('cat', 'dog', 'horse', 'elephant');
foreach($animals as $animal)
{
var_dump($animal);
next($animals);
}
上面的代码输出:cat、dog、horse、elephant。我以为next
函数应该移动内部指针$animals
因此,我应该得到这个输出:猫,马。
如何使 $animals 的内部指针向前(和向后)移动,以便在 foreach 中受到影响?
EDIT 1:
从手册中:
由于 foreach 依赖于内部数组指针,因此在
循环可能会导致意外的行为。
尽管如此,我认为这就是我需要做的。
EDIT 2:
根据“您的常识”的链接,我将为我的问题提供更详细的解释。这是一些伪代码:
array $foos;
start loop of $foos
- do thing #1
- do thing #2
- do thing #3
- keep doing thing #3 while the current value of $foos in the loop meets a certain criteria
loop
当执行返回到循环开始时,它应该从 #3 访问的最后一个数组继续。注意数组是关联的,因此for ($i = 0 ...
方法行不通。
You can just create an ArrayIteratorDocs http://php.net/ArrayIterator which is seekableDocs http://php.net/SeekableIterator.
由于它是一个迭代器,因此您可以更改position while你迭代它,一些基本的例子:
foreach ($iterator as $current) {
$iterator->next();
}
It should offer everything you need out of the box. If not, you could encapsulate your needs into an IteratorDocs http://php.net/class.iterator on your own as well.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)