2012-01-17 72 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