2011-07-10 94 views
0

我有一個數組中的「foo.bar.baz」作爲鍵名。有沒有一種方便的方法將這個數組變成一個多維數組(使用每個「點級」作爲下一個數組的鍵)?Array to multidimensional array ...基於foo.bar.baz-dots數組鍵名

  • 實際輸出:陣列([foo.bar.baz] => 1,[qux] => 1)
  • 希望的輸出:陣列([富] [巴] [巴茲] => 1, [qux] => 1)

代碼例如:

$arr = array("foo.bar.baz" => 1, "qux" => 1); 
print_r($arr); 

回答

3

解決方案:

<?php 

$arr = array('foo.bar.baz' => 1, 'qux' => 1); 

function array_dotkey(array $arr) 
{ 
    // Loop through each key/value pairs. 
    foreach ($arr as $key => $value) 
    { 
    if (strpos($key, '.') !== FALSE) 
    { 
     // Reference to the array. 
     $tmparr =& $arr; 

     // Split the key by "." and loop through each value. 
     foreach (explode('.', $key) as $tmpkey) 
     { 
     // Add it to the array. 
     $tmparr[$tmpkey] = array(); 

     // So that we can recursively continue adding values, change $tmparr to a reference of the most recent key we've added. 
     $tmparr =& $tmparr[$tmpkey]; 
     } 

     // Set the value. 
     $tmparr = $value; 

     // Remove the key that contains "." characters now that we've added the multi-dimensional version. 
     unset($arr[$key]); 
    } 
    } 

    return $arr; 
} 

$arr = array_dotkey($arr); 
print_r($arr); 

輸出:

Array 
(
    [qux] => 1 
    [foo] => Array 
     (
      [bar] => Array 
       (
        [baz] => 1 
       ) 

     ) 

) 
+0

+1我無法找出答案:) – AlienWebguy

+0

尼斯。你可以把它放到一個函數中嗎?像array_dotkey($ value,&$ tmparr){...} –

+0

@Kristoffer Bohmann - 你當然可以,但我會建議創建一個接受數組的函數。我會更新答案。 –