检测PHP中的无限数组递归?

lee*_*iya 14 php reflection recursion detect

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

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

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

对于数组递归检测,我有点困惑,我没有发现任何有用的东西.php本身能够识别递归,虽然它似乎太晚了一个周期.编辑:nvm,它发生在它需要的地方:)

$arr = array();
$arr[] = array(&$arr);
print_r($arr);
Run Code Online (Sandbox Code Playgroud)

它是否必须求助于跟踪递归堆栈中的所有内容并对每个其他数组元素进行浅层比较?

任何帮助将不胜感激,
谢谢!

nic*_*ass 9

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

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']);

}
Run Code Online (Sandbox Code Playgroud)

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