1

我有几个数组如下:

$files = Array ('dir1/dir2/dir3/file1', 
            'dir1/dir2/dir3/file2', 
            'dir1/dir2/dir3/file3',
            'dir1/dir2/dir3/file4'
        );

我徒劳地尝试了几个递归函数来转换如下:

$files = Array (
        'dir1' => Array (
                'dir2' => Array (
                            'dir3' => Array (
                                        'file1', 
                                        'file2', 
                                        'file3', 
                                        'file4'
                             )
                 )
         )
);

请帮我

4

1 回答 1

1

你的意思是这样的:

$files = array('dir1/dir2/dir3/file1', 
            'dir1/dir2/dir3/file2', 
            'dir1/dir2/dir3/file3',
            'dir1/dir2/dir3/file4'
);


$newFiles = array();
foreach($files as $file){
    $one = explode('/', $file);       // explode '/' to get each value
    $last = array_pop($one);          // pop the last item because it is the file
    $rev = array_reverse($one);       // we reverse the array in order to append the last to previous
    $mixArray = array();              // create a temporary array

    foreach($rev as $num => $dir){    // loop in reversed array to extract directories

        $mixArray[$dir] = $last;      // append the last item to the current dir, the first loop puts the file to the last directory
        $last = $mixArray;            // overwrite last variable with current created array

        if($num < count($rev)-1){ 
            unset($mixArray);         // if the current directory is not the last in reversed array we unset it because we will have duplicates
        }
    }

    $newFiles = array_merge_recursive($newFiles, $mixArray); // merge recursive the result to main array
}

var_export($newFiles);

键盘示例

于 2012-09-06T08:16:15.163 回答