2012-01-17 83 views
0

我需要一个函数/类方法,它可以在数组中找到一个元素(在包含所述元素位置的另一个数组的帮助下)并返回对它的引用。函数接受对数组的引用,搜索数组并返回对搜索结果的引用?

无济于事我试图做到这一点,像这样:

$var = array("foo" => array("bar" => array("bla" => "goal"))); 

$location = array("foo", "bar", "bla"); 

... 

$ref =& $this->locate($var, $location); 

... 

private function &locate(&$var, $location) { 

    if(count($location)) 

     $this->locate($var[array_shift($location)], $location); 

    else 

     return $var; 

} 

以上函数成功地找到了“目标”,但参考不返回到$裁判,而不是$裁判是空的。

任何帮助非常感谢,这严重阻止我完成我的工作。谢谢。

回答

0

你需要越过结果到递归栈到第一个呼叫:

private function &locate(&$var, $location) { 
    if(count($location)) { 
     $refIndex= array_shift($location); 
     return $this->locate($var[$refIndex], $location); 
    } else { 
     return $var; 
    } 
} 

和递归调用之前我会做array_shift电话。你知道,我对调用中参数发生变化的函数调用感到不自在。

+0

参数在函数调用之前进行评估,所以当参数有变异表达式时(实际上,当它们有任何副作用时),这不是问题。 – outis 2012-01-17 12:21:30

+0

非常感谢,我完全忽略了这一点。我在你的债务! – Ozonic 2012-01-17 12:27:23