PHP foreach SplPriorityQueue - 找不到元素

发布于 2024-12-22 19:54:15 字数 349 浏览 2 评论 0原文

我有以下代码:

    $friendsOrdered= new SplPriorityQueue();
    ... // Code to fill up the priority queue
    print_r($friendsOrdered);
    $i = 0;
    foreach($friendsOrdered as $f) {
    }
    echo "<br><br>";
    print_r($friendsOrdered);

当我查看打印的输出时,我可以看到循环之后优先级队列为空。有没有办法阻止 foreach 删除元素?

谢谢!

I have the following code:

    $friendsOrdered= new SplPriorityQueue();
    ... // Code to fill up the priority queue
    print_r($friendsOrdered);
    $i = 0;
    foreach($friendsOrdered as $f) {
    }
    echo "<br><br>";
    print_r($friendsOrdered);

When I look at the output of the prints I can see that after the loop the priority queue is empty. Is there a way of stopping the foreach from removing elements?

Thanks!

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

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

发布评论

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

评论(1

一桥轻雨一伞开 2024-12-29 19:54:15

您无法阻止循环使元素出队,因为这是数据结构的本质。但是,您可以在循环之前创建对象的副本,这样您的数据就不会丢失:

$friendsOrdered_copy = clone $friendsOrdered;
foreach($friendsOrdered_copy as $f) {
    // ...
}

You cannot stop the loop from dequeuing elements, as that is the nature of the data structure. You could, however, create a copy of the object before the loop so your data isn't lost:

$friendsOrdered_copy = clone $friendsOrdered;
foreach($friendsOrdered_copy as $f) {
    // ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文