检测 PHP 中的无限数组递归?
我刚刚在我的宠物项目 dump_r()
https://github.com/leeoniya/dump_r.php< /a>
检测对象递归并不是太困难 - 您使用 spl_object_hash() 来获取对象实例的唯一内部 id,将其存储在字典中并在转储其他节点时与其进行比较。
对于数组递归检测,我有点困惑,我没有发现任何有用的东西。 php 本身能够识别递归,尽管它似乎晚了一个周期。 编辑:nvm,它发生在需要的地方:)
$arr = array();
$arr[] = array(&$arr);
print_r($arr);
它是否必须跟踪递归堆栈中的所有内容并与每个其他数组元素进行浅比较?
任何帮助将不胜感激,
谢谢!
i've just reworked my recursion detection algorithm in my pet project dump_r()
https://github.com/leeoniya/dump_r.php
detecting object recursion is not too difficult - you use spl_object_hash() to get the unique internal id of the object instance, store it in a dict and compare against it while dumping other nodes.
for array recursion detection, i'm a bit puzzled, i have not found anything helpful. php itself is able to identify recursion, though it seems to do it one cycle too late. EDIT: nvm, it occurs where it needs to :)
$arr = array();
$arr[] = array(&$arr);
print_r($arr);
does it have to resort to keeping track of everything in the recursion stack and do shallow comparisons against every other array element?
any help would be appreciated,
thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于 PHP 的按值调用机制,我在这里看到的唯一解决方案是通过引用迭代数组,并在其中设置任意值,稍后检查它是否存在以查明您之前是否存在:
您可以将此函数包装到另一个接受值而不是引用的函数中,但随后您将从第二级开始收到 RECURSION 通知。我认为 print_r 也做了同样的事情。
Because of PHP's call-by-value mechanism, the only solution I see here is to iterate the array by reference, and set an arbitrary value in it, which you later check if it exists to find out if you were there before:
You could wrap this function into another function that accepts values instead of references, but then you would get the RECURSION notice from the 2nd level on. I think print_r does the same too.
如果我错了,有人会纠正我,但 PHP 实际上在正确的时刻检测到递归。您的分配只会创建额外的周期。该示例应该是:
这将导致
正如预期的那样。
好吧,我自己有点好奇如何检测递归,然后我开始谷歌。我发现这篇文章 http://noteslog.com/post/ detector-recursive-dependency-in-php-composite-values/ 和这个解决方案:
Someone will correct me if I am wrong, but PHP is actually detecting recursion at the right moment. Your assignation simply creates the additional cycle. The example should be:
Which will result in
As expected.
Well, I got a bit curious myself how to detect recursion and I started to Google. I found this article http://noteslog.com/post/detecting-recursive-dependencies-in-php-composite-values/ and this solution: