在PHP中检测无限数组递归? [英] detecting infinite array recursion in PHP?

查看:42
本文介绍了在PHP中检测无限数组递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在我的宠物项目dump_r()中重新设计了递归检测算法

i've just reworked my recursion detection algorithm in my pet project dump_r()

https://github.com/leeoniya/dump_r.php

检测对象递归不是很困难-您使用spl_object_hash()获取对象实例的唯一内部ID,将其存储在dict中并在转储其他节点时与之进行比较.

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.

对于数组递归检测,我有点困惑,我没有发现任何有用的东西.php本身可以识别递归,尽管它似乎做不到一个周期.nvm,它出现在需要的地方:)

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. 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!

推荐答案

由于PHP的按值调用机制,我在这里看到的唯一解决方案是通过引用迭代数组,并在其中设置任意值,您稍后再检查是否存在,以了解您之前是否曾经在这里:

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:

function iterate_array(&$arr){

  if(!is_array($arr)){
    print $arr;
    return;
  }

  // if this key is present, it means you already walked this array
  if(isset($arr['__been_here'])){
    print 'RECURSION';
    return;
  }

  $arr['__been_here'] = true;

  foreach($arr as $key => &$value){

    // print your values here, or do your stuff
    if($key !== '__been_here'){
      if(is_array($value)){
        iterate_array($value);
      }

      print $value;
    }
  }

  // you need to unset it when done because you're working with a reference...
  unset($arr['__been_here']);

}

您可以将此函数包装到另一个接受值而不是引用的函数中,但是从第二层开始,您将获得RECURSION通知.我认为print_r也是一样.

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中检测无限数组递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆