2013-11-14 75 views
4

我可以得到幫助,知道這是否可能嗎?我想選擇動態數組。php通過路徑選擇陣列

例如,

$oj = (object)['A' => (object)['B' => (object)['C' => (object)['D' => []]]]] 

$E = 'A' 
$oj->$E // this will work 

$E = 'A->B' 
$oj->$E // this will not work 

除了寫一個完整的路徑我還有什麼可以做?或者,也許請告訴我,這是可能的,還是有任何我可以提及的例子?

$oj[A][B][C][D]  <---NO 
$oj->A->B->C->D  <---NO 

$E = A->B->C->D  
$oj->E    <--What I want 


Question Update: 

$oj->E = 'Store something' <-What I want, then will store into $oj. 

//So E here is not pick up the value of D, but the path of D; 

非常感謝。

+0

尋找這個'$ oj [A [B [C [D]]]]'? – alfasin

回答

3

您可以通過->通過路徑的一部分爆炸路徑和跟蹤對象部分:

function getPath($obj,$path) { 
    foreach(explode('->',$path) as $part) $obj = $obj->$part; 
    return $obj; 
} 

$oj = (object)['A' => (object)['B' => (object)['C' => (object)['D' => []]]]]; 
$E = 'A->B->C->D'; 
getPath($oj,$E); 

如果你也想寫點什麼,你可以做到這一點醜陋,但使用簡單的方法eval

eval("\$tgt=&\$oj->$E;"); // $tgt is the adress of $oj->A->B->C->D->E 
print_r($tgt); // original value of $oj->A->B->C->D->E 
$tgt = "foo"; 
print_r($oj); // $oj->A->B->C->D->E = "foo" 
+0

非常感謝你,問題更新,你的例子只會拿起D的價值,而我想要的是選擇路徑 – Till

+0

@Till:我已經更新了答案 –

+0

非常感謝! – Till

2

簡短的回答:沒有。

長答案:

您是否在尋找references?好的,可能不是。

在任何情況下,你可能會更好過寫你自己的一套類或功能,例如:

setUsingPath($oj, 'A->B->C->D', $x); 
$x = getUsingPath($oj, $E); 

但是,如果你確定你想要的是在(未指定的)問題的最佳解決方案和$E = 'A->B'; $oj->E...是一起去的語法,應該可以用不寒而慄magic methods。一套遞歸的不寒而慄__get() s應該訣竅。