2013-02-28 63 views
4

我有以下陣列:轉換字符串數組,每個字符串具有點分隔值,以多維數組

Array 
(
    [0] => INBOX.Trash 
    [1] => INBOX.Sent 
    [2] => INBOX.Drafts 
    [3] => INBOX.Test.sub folder 
    [4] => INBOX.Test.sub folder.test 2 
) 

我怎麼可以這樣數組轉換爲一個多維數組是這樣的:

Array 
(
    [Inbox] => Array 
     (
      [Trash] => Array 
       (
       ) 

      [Sent] => Array 
       (
       ) 

      [Drafts] => Array 
       (
       ) 

      [Test] => Array 
       (
        [sub folder] => Array 
         (
          [test 2] => Array 
           (
           ) 

         ) 

       ) 

     ) 

) 
+2

[你嘗試過什麼?](http://whathaveyoutried.com)[字符串的 – 2013-02-28 10:08:07

+1

可能重複與陣列結構陣列](http://stackoverflow.com/questions/8537148/string-with-array-structure-to-array) – Jon 2013-02-28 10:32:44

+0

我很難試圖做到這一點!會很酷,看到一個答案.. – 2013-02-28 10:36:43

回答

4

試試這個。

<?php 
$test = Array 
(
    0 => 'INBOX.Trash', 
    1 => 'INBOX.Sent', 
    2 => 'INBOX.Drafts', 
    3 => 'INBOX.Test.sub folder', 
    4 => 'INBOX.Test.sub folder.test 2', 
); 

$output = array(); 
foreach($test as $element){ 
    assignArrayByPath($output, $element); 
} 
//print_r($output); 
debug($output); 
function assignArrayByPath(&$arr, $path) { 
    $keys = explode('.', $path); 

    while ($key = array_shift($keys)) { 
     $arr = &$arr[$key]; 
    } 
} 

function debug($arr){ 
    echo "<pre>"; 
    print_r($arr); 
    echo "</pre>"; 
} 
+0

+1爲好的解決方案:) – 2013-02-28 11:21:27

0

我對此非常感興趣,因爲試圖做到這一點非常困難。看着(和經歷),喬恩的解決方案後,我想出了這一點:

$array = array(); 
function parse_folder(&$array, $folder) 
{ 
    // split the folder name by . into an array 
    $path = explode('.', $folder); 

    // set the pointer to the root of the array 
    $root = &$array; 

    // loop through the path parts until all parts have been removed (via array_shift below) 
    while (count($path) > 1) { 
     // extract and remove the first part of the path 
     $branch = array_shift($path); 
     // if the current path hasn't been created yet.. 
     if (!isset($root[$branch])) { 
      // create it 
      $root[$branch] = array(); 
     } 
     // set the root to the current part of the path so we can append the next part directly 
     $root = &$root[$branch]; 
    } 
    // set the value of the path to an empty array as per OP request 
    $root[$path[0]] = array(); 
} 

foreach ($folders as $folder) { 
    // loop through each folder and send it to the parse_folder() function 
    parse_folder($array, $folder); 
} 

print_r($array);