我使用RecursiveIteratorIterator迭代一个多维数组,并希望能够知道当前元素是否是其深度的最后一个子元素。我想到了这个:
$iterator = new RecursiveIteratorIterator($array,
RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $val) {
$next = clone $iterator;
$next->next();
$lastChild = ($next->getDepth() < $iterator->getDepth());
}
但是RecursiveIteratorIterator说它不可复制。
答案 0 :(得分:11)
短语“深度的最后一个孩子”并不是特别清楚。你能详细说明你的意思吗?这个的预期用途?
如果你的意思很简单,深度会在当前元素之后改变,那么(Recursive)CachingIterator
有一个方便的hasNext
方法来确定迭代器是否还有其他项。给出一个与问题类似的淡化示例:
$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";
}
}
输出:
6 is the last child!
8 is the last child!
3 is the last child!
5 is the last child!