我通过与RecursiveIteratorIterator多维数组迭代,并希望能够知道,如果目前的元素是它的深度的最后一个孩子。我考虑这样的:

$iterator = new RecursiveIteratorIterator($array,
  RecursiveIteratorIterator::SELF_FIRST);    
foreach ($iterator as $val) {
  $next = clone $iterator;
  $next->next();
  $lastChild = ($next->getDepth() < $iterator->getDepth());
}

但RecursiveIteratorIterator说,这是不可复制的。

有帮助吗?

解决方案

短语“其深度的最后一个子”是不是特别清楚。你能解释一下你的意思正是;这样做的预期用途

如果你的意思是,很简单,即深度将当前元素后更改,那么(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!
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top