2014-01-27 125 views
1

我有一個多維數組,這裏是一個小摘錄:字符串多維數組路徑

Array (
    [Albums] => Array (
     [A Great Big World - Is There Anybody Out There] => Array(...), 
     [ATB - Contact] => Array(...), 
    ) 
    [Pop] => Array (...) 
) 

而且我有一個動態的路徑:

/albums/a_great_big_world_-_is_there_anybody_out_there 

什麼是檢索的最佳方式(在這個例子中)$arr["albums"]["A Great Big World - Is There Anybody Out There"]

請注意它應該是動態的,因爲在這個例子中嵌套可以比2層更深。

編輯

下面是我用它來創建用於URL簡單的字符串函數:

function formatURL($url) { 
    return preg_replace('/__+/', '_', preg_replace('/[^a-z0-9_\s-]/', "", strtolower(str_replace(" ", "_", $url)))); 
} 

回答

0
$array = array(...); 
$path = '/albums/a_great_big_world_-_is_there_anybody_out_there'; 

$value = $array; 
foreach (explode('/', trim($path, '/')) as $key) { 
    if (isset($value[$key]) && is_array($value[$key])) { 
     $value = $value[$key]; 
    } else { 
     throw new Exception("Path $path is invalid"); 
    } 
} 

echo $value; 
+0

這個循環的作品,但在我的陣列的孩子是不是叫'/albums/a_great_big_world _-_ is_there_anybody_out_there',它是'/相冊/一個偉大的大世界 - 有沒有人在那裏。任何方式來輕鬆解決這個問題,或者我更好地重寫數組創建? –

+1

嗯,是的,沒有明顯的方法來將一個較低的下劃線的弦變成一個套弦。如果你*有*顯而易見的方式,去做吧。或者,如果您有一臺發電機,可以將套管間距的絃線轉換爲下部箱體的下弦絃線,則可以使用其他方法。但是堅持使用相同的獨特IDs總是比嘗試匹配兩個不匹配的東西更好的選擇。重寫你的數組。 – deceze

+0

是的,我想我會在我的主帖中使用'formatURL'函數。謝謝您的幫助! –