1

你好,只是在寻求帮助,因为我被卡住了

我有两个字符串:

C:\Users\Bob\My Documents
/Users/Bob/Documents

这得到通过

preg_split('/(?<=[\/\\\])(?![\/\\\])/', $string)

返回

Array
(
    [0] => C:\
    [1] => Users\
    [2] => Bob\
    [3] => My Documents
)

Array
(
    [0] => /
    [1] => Users/
    [2] => Bob/
    [3] => Documents
)

我需要

Array
(
    [C:\] => Array
        (
            [Users] => Array
                (
                    [Bob] => Array
                        (
                            [My Documents] => array()
                        )

                )

        )

)

Array
(
    [/] => Array
        (
            [Users] => Array
                (
                    [Bob] => Array
                        (
                            [Documents] => array()
                        )

                )

        )

)

并最终合并为

Array
(
    [C:\] => Array
        (
            [Users] => Array
                (
                    [Bob] => Array
                        (
                            [My Documents] => array()
                        )

                )

        )
    [/] => Array
        (
            [Users] => Array
                (
                    [Bob] => Array
                        (
                            [Documents] => array()
                        )

                )

        )

)

(正确合并,而不仅仅是附加,所以如果另一个字符串以C:\Users\DanThen dan 开头,则会出现在第 3 个?维度。array_merge_recursive()?)

4

2 回答 2

1

只需获取返回的数组preg_split()并从中构建您的树结构:

$tree = array();
foreach ( $strings as $string ) {
    $path = preg_split( '/(?<=[\/\\\])(?![\/\\\])/', $string );
    $ptr =& $tree;
    foreach ( $path as $elem ) {
        if ( ! array_key_exists( $elem, $ptr ) )
            $ptr[ $elem ] = array();
        $ptr =& $ptr[ $elem ];
    }
}
于 2011-10-04T18:42:57.637 回答
0

你可能最好只使用 pathinfo()

http://uk.php.net/manual/en/function.pathinfo.php

和 realpath() http://uk.php.net/manual/en/function.realpath.php

我假设您正在尝试将 *nix 目录映射到 Windows 目录?

于 2011-10-04T17:49:50.077 回答