RecursiveIteratorIterator último hijo
Pregunta
iterar a través de una matriz multidimensional con RecursiveIteratorIterator y me gustaría ser capaz de saber si el elemento actual es el último hijo de ella de profundidad. Pensé en esto:
$iterator = new RecursiveIteratorIterator($array,
RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $val) {
$next = clone $iterator;
$next->next();
$lastChild = ($next->getDepth() < $iterator->getDepth());
}
Pero el RecursiveIteratorIterator dice que no es cloneable.
Solución
La frase "último hijo de su profundidad" no es particularmente claro. Podría explicar precisamente lo que quiere decir; el uso previsto para esto?
Si usted quiere decir, simplemente, que la profundidad va a cambiar después de que el elemento actual, entonces el (Recursive)CachingIterator
tiene un método hasNext
útil para determinar si el iterador tiene ningún artículo adicional. Para dar un ejemplo aguada similar a la de la pregunta:
$array = array(
range(1,6),
range(7,8),
'foo' => range(1,3),
'bar' => range(4,5),
);
$rit = new RecursiveArrayIterator($array);
$iterator = new RecursiveIteratorIterator(
new RecursiveCachingIterator($rit),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($iterator as $val) {
$lastChild = !$iterator->hasNext();
if ($lastChild) {
echo "$val is the last child!\n";
}
}
Salidas:
6 is the last child!
8 is the last child!
3 is the last child!
5 is the last child!
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow