【问题标题】:Get complete file path from an array从数组中获取完整的文件路径
【发布时间】:2011-06-24 01:24:05
【问题描述】:

我有这个数组(它来自一个特定的功能:列出和过滤扩展目录的文件):

Array
(
    [Dir_test] = Array
        (
            [dir_client] = Array
                (
                    [0] = index.html
                )

            [0] = index.html
        )
)

我想得到类似的东西。注意:该目录可能有更多的子目录。

Array
(
    [0] = Dir_test/dir_client/index.html
    [1] = Dir_test/index.html
)

感谢您的帮助;)

【问题讨论】:

标签: php arrays file recursion directory


【解决方案1】:

假设您的输入数据如下所示:

$arr = array(
    'Dir_test' => array (
        'dir_client' => array (
            0 => 'index.html'
        ),

        0 => 'index.html'
    )
);

最简单的解决方案是递归解决方案,例如:

function add_dir($dir) {
    global $dirs;

    $dirs[] = $dir;
}

// pathsofar should always end in '/'
function process_dir($dirarray, $pathsofar) {
    foreach ($dirarray as $key => $value) {
        if (is_array($value)) {
            process_dir($value, $pathsofar . $key . '/');
        } else {
            add_dir($pathsofar . $value);
        }
    }
}

process_dir($arr, '');

print_r($dirs);

运行它:

$ php arr2.php
Array
(
    [0] => Dir_test/dir_client/index.html
    [1] => Dir_test/index.html
)

【讨论】:

    【解决方案2】:

    你可以使用array_walk_recursive函数

    【讨论】:

      【解决方案3】:

      编写一个递归函数,它接受一个数组和一个字符串作为参数,并在数组的每个键上返回并调用自身。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-17
        • 1970-01-01
        • 2012-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-24
        相关资源
        最近更新 更多