First and last elements in list using RecursiveIteratorIterator
-
13-10-2019 - |
Pergunta
I'm using RecursiveIteratorIterator
to loop over Zend_Navigation
, which is basically a list of nested <ul>
and <li>
tags:
$iterator = new RecursiveIteratorIterator(
$container,
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($iterator as $page) {
...
// isLast()?
// isFirst()?
}
How to determine, whether the currently iterated element ($page
) is first or last element on current level?
I need to add first
and last
class attribute to those elements.
Solução
You could use getDepth() to query the depth of the tag. When the depth increases, you're at a new level and should add a first
attribute. When the depth decreases between tags, that tells you the previous tag was the last in its level and you should add a last
attribute to it. This means you will have to read the next tag before you can finish processing the current tag.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow