2011-01-30 94 views
1

我有一個多維數組,其中這個作品:PHP變量數組變量鍵列表

print_r($temp[1][0]); 

我怎樣才能使這項工作...我有鑰匙的列表,像這樣的字符串:

$keys = "[1][0]"; 

我想訪問使用鍵列表的字符串列表,它是如何做到的? 這工作,但按鍵有明顯硬編碼:

$keys = "[1][0]"; 
$tempName = 'temp'; 

print_r(${$tempName}[1][0]); 

// tried lots of variations like, but they all produce errors or don't access the array 
print_r(${$tempName.${$keys}}); 

謝謝, 克里斯

+0

恭喜。你剛剛設置了我的新個人記錄,以便根據我在SO上看到的基本上破碎的想法/代碼。 「變量變量很整齊,但讓我們看看我們可以帶他們走多遠......」 – delnan 2011-01-30 12:43:25

回答

4
function accessArray(array $array, $keys) { 
    if (!preg_match_all('~\[([^\]]+)\]~', $keys, $matches, PREG_PATTERN_ORDER)) { 
     throw new InvalidArgumentException; 
    } 

    $keys = $matches[1]; 
    $current = $array; 
    foreach ($keys as $key) { 
     $current = $current[$key]; 
    } 

    return $current; 
} 

echo accessArray(
    array(
     1 => array(
      2 => 'foo' 
     ) 
    ), 
    '[1][2]' 
); // echos 'foo' 

會更好,如果你在array(1, 2)傳遞,而不是[1][2],:一可避免的(脆弱)preg_match_all解析。

+0

我喜歡這種方法,因爲它優雅而安全。 – 2011-01-30 12:48:58