RecursiveIteratorIterator 最后一个孩子

发布于 2024-09-24 21:22:21 字数 393 浏览 7 评论 0原文

我使用 RecursiveIteratorIterator 迭代多维数组,并希望能够知道当前元素是否是其深度的最后一个子元素。我想到了这一点:

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

但是 RecursiveIteratorIterator 说它不可克隆。

I iterate through a multidimensional array with RecursiveIteratorIterator and would like to be able to know if the current element is the last child of it's depth. I thought about this:

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

But the RecursiveIteratorIterator says it's not cloneable.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你丑哭了我 2024-10-01 21:22:21

“其深度的最后一个孩子”这句话并不是特别清楚。您能详细说明一下您的意思吗?其预期用途?

如果您的意思很简单,深度将在当前元素之后发生变化,那么(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!

The phrase "last child of its depth" is not particularly clear. Could you elaborate on precisely what you mean; the intended use for this?

If you mean, quite simply, that the depth will change after the current element, then the (Recursive)CachingIterator has a handy hasNext method to determine whether the iterator has any further items. To give a watered-down example similar to that in the question:

$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";
    }
}

Outputs:

6 is the last child!
8 is the last child!
3 is the last child!
5 is the last child!
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文