這是一種常見的實現問題。如果我有一個任意深度的數組,並且事先不知道密鑰是什麼,那麼訪問關聯數組的特定路徑上的值的最佳方法是什麼?例如,假設數組:從關聯數組中獲取嵌套值
array(
'great-grandparent' = array(
'grandparent' = array(
'parent' = array(
'child' = 'value';
),
'parent2' = 'value';
),
'grandparent2' = 'value';
)
);
請告訴我在$array['great-grandparent']['grandparent']['parent']['child']
牢記,我不知道該組鍵來訪問值的最佳方式。我已經使用eval將上面的語法構造爲具有變量名稱的字符串,然後評估字符串以獲取數據。但eval是緩慢的,我希望更快的事情。喜歡的東西$class->getConfigValue('great-grandparent/grandparent/'.$parent.'/child');
,將返回「價值」
評估和演示代碼示例
public function getValue($path, $withAttributes=false) {
$path = explode('/', $path);
$rs = '$r = $this->_data[\'config\']';
foreach ($path as $attr) {
$rs .= '[\'' . $attr . '\']';
}
$rs .= ';';
$r = null;
@eval($rs);
if($withAttributes === false) {
$r = $this->_removeAttributes($r);
}
return $r;
}
您是evaling?你能向我們展示一個例子嗎? – 2011-03-25 21:43:51
添加了評估代碼。它基本上採用/定界的路徑,並將其轉換爲數組訪問語法,然後進行評估。 – chris 2011-03-25 21:50:01
你正在用這個實現一個配置系統嗎? – 2011-03-25 21:50:28