simple array into associative array, based on 'directory tree' like values of the first one

好久不见. 提交于 2019-12-13 02:49:43

问题


For example, I have array

Array
(
    [0] => folder1/file1.txt
    [1] => folder1/file2.txt
    [2] => file2.txt
    [3] => folder2/file1.txt
    [4] => folder1/subfolder1/file1.txt
    [5] => folder1/subfolder2/file2.txt
    [6] => file1.txt
    [7] => file3.txt
    [8] => folder1/subfolder2/file1.txt
)

I need a clue to figure how to create 'directory tree' array, based on the given values, that it could look like this:

Array
(
    [folder1] => Array
        (
            [0] => file1.txt
            [1] => file2.txt
            [subfolder1] => Array
                (
                    [0] => file1.txt
                )

            [subfolder2] => Array
                (
                    [0] => file1.txt
                    [1] => file2.txt
                )

        )

    [0] => file1.txt
    [1] => file2.txt
    [2] => file3.txt
)

Now second array is a tree of the first array (made manually). =)

And I can't figure how to achieve this automatically.


回答1:


Simples example (demo), that will generate output like you wish, but you will get conflict if you will have same folder and file name in the same directory level (demo).

$files = [
    'folder1/file1.txt',
    'folder1/file2.txt',
    'file2.txt',
    'folder2/file1.txt',
    'folder1/subfolder1/file1.txt',
    'folder1/subfolder2/file2.txt',
    'file1.txt',
    'file3.txt',
    'folder1/subfolder2/file1.txt',
];

$tree = [];
foreach ($files as $file) {
    $a = explode('/', $file);
    $array = &$tree;
    foreach (array_slice($a, 0, -1) as $folder) {
        if (!isset($array[$folder])) $array[$folder] = [];
        $array = &$array[$folder];
    }
    $array[] = end($a);
}
print_r($tree);

To overcome problem with same folder and file named on the same level you can create folder indexes with slash at the end, like folder/, so there cannot be any conflict (demo).



来源:https://stackoverflow.com/questions/19141998/simple-array-into-associative-array-based-on-directory-tree-like-values-of-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!