2009-09-13 103 views
2

我想創建一個多維數組,其部分由字符串決定。我使用.作爲分隔符,各部分(除最後一個)應該是一個數組
例如:如何遞歸創建一個多維數組?

config.debug.router.strictMode = true 

我想同樣的結果,好像我是鍵入:

$arr = array('config' => array('debug' => array('router' => array('strictMode' => true)))); 

這個問題真的讓我在圈子裏,任何幫助表示讚賞。謝謝!

回答

4

假設我們已經在$key$val鍵和值,那麼你可以這樣做:

$key = 'config.debug.router.strictMode'; 
$val = true; 
$path = explode('.', $key); 

Builing數組中從左至右依次爲:

$arr = array(); 
$tmp = &$arr; 
foreach ($path as $segment) { 
    $tmp[$segment] = array(); 
    $tmp = &$tmp[$segment]; 
} 
$tmp = $val; 

,由右左:

$arr = array(); 
$tmp = $val; 
while ($segment = array_pop($path)) { 
    $tmp = array($segment => $tmp); 
} 
$arr = $tmp; 
4

我說把所有東西都分開,先從值開始,然後從那裏開始往回運行,每次都是,把你在另一個數組中的內容包裝起來。像這樣:

$s = 'config.debug.router.strictMode = true'; 
list($parts, $value) = explode(' = ', $s); 

$parts = explode('.', $parts); 
while($parts) { 
    $value = array(array_pop($parts) => $value); 
} 

print_r($parts); 

絕對重寫它,所以它有錯誤檢查。

+0

這很好,但我很好奇,我應該檢查可能的錯誤。 – 2009-09-13 06:57:06

+0

如果你想解析/存儲多行文件,這看起來好像中斷了。 – timdev 2009-09-13 07:08:51

+0

武器:例如,如果該行中沒有「=」,則會斷開。基本上,與語法不匹配的行完全導致我的腳本拋出php錯誤。你會想讓它變得更寬容(比如不需要等號旁邊的空格)並以某種有意義的方式處理錯誤,而不是php錯誤,比如「foreach()的無效參數」。 – JasonWoof 2009-09-13 07:13:13

0
// The attribute to the right of the equals sign 
$rightOfEquals = true; 

$leftOfEquals = "config.debug.router.strictMode"; 

// Array of identifiers 
$identifiers = explode(".", $leftOfEquals); 

// How many 'identifiers' we have 
$numIdentifiers = count($identifiers); 


// Iterate through each identifier backwards 
// We do this backwards because we want the "innermost" array element 
// to be defined first. 
for ($i = ($numIdentifiers - 1); $i >=0; $i--) 
{ 

    // If we are looking at the "last" identifier, then we know what its 
    // value is. It is the thing directly to the right of the equals sign. 
    if ($i == ($numIdentifiers - 1)) 
    { 
     $a = array($identifiers[$i] => $rightOfEquals); 
    } 
    // Otherwise, we recursively append our new attribute to the beginning of the array. 
    else 
    { 
     $a = array($identifiers[$i] => $a); 
    } 

} 

print_r($a); 
1

Gumbo的回答看起來不錯。

但是,它看起來像你想解析一個典型的.ini文件。

考慮使用庫代碼而不是滾動自己的代碼。

例如,Zend_Config很好地處理這種事情。

1

我真的很喜歡JasonWolf對此的回答。

至於可能的錯誤:是的,但他提供了一個好主意,現在是讀者做出防彈的決定。

我的需求是更基本的:從分隔列表中創建一個MD數組。我稍微修改了他的代碼,以便讓我知道。這個版本會給你一個有或沒有定義字符串的數組,或者甚至沒有定界符的字符串。

我希望有人可以做得更好。

$parts = "config.debug.router.strictMode"; 

$parts = explode(".", $parts); 

$value = null; 

while($parts) { 
    $value = array(array_pop($parts) => $value); 
} 


print_r($value);