数组PHP的完整路径列表

时间:2013-12-04 12:15:16

标签: php glob

我从递归的glob函数中得到了路径列表......类似于

/a/b/aaaa.txt
/c/d/bbbb.txt
/a/z/dddd.txt
/a/b/c/d/yyyy.txt

将这些放入数组的最简单方法是什么:

$a[a][b][] = aaaa.txt
$a[c][d][] = bbbb.txt
$a[a][z][] = dddd.txt
$a[a][b][c][d][] = yyyy.txt

2 个答案:

答案 0 :(得分:1)

如果你掌握了recursion的概念,这听起来像是一项家庭作业测试。一旦你围绕这个概念,这种问题就很容易解决。

$paths = array(
    '/a/b/aaaa.txt',
    '/c/d/bbbb.txt',
    '/a/z/dddd.txt',
    '/a/b/c/d/yyyy.txt',
);

$a = array();


foreach ($paths as $path)
{
    $newArray = buildArrayFromPath($path);
    $a = array_merge_recursive($a, $newArray);
}

/**
 * Make an array from a path string
 */
function buildArrayFromPath($path)
{
    $path = trim($path, '/');
    $parts = explode('/', $path);

    return recursiveBuildArray($parts);
}

/**
 * Recursively build a multidimensional array from path parts
 */
function recursiveBuildArray(array $left, $new = array())
{
    $key = array_shift($left);

    if (count($left) > 1) {

        $new[$key] = recursiveBuildArray($left, $new);
    }
    else {
        $new[$key][] = array_pop($left);
    }

    return $new;
}

// check if we got back the expected result
$benchmark['a']['b'][] = 'aaaa.txt';
$benchmark['c']['d'][] = 'bbbb.txt';
$benchmark['a']['z'][] = 'dddd.txt';
$benchmark['a']['b']['c']['d'][] = 'yyyy.txt';

// TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
var_dump($a === $benchmark);

答案 1 :(得分:0)

完全递归的解决方案,我需要合并2个glob数组时使用它。所有重复项只插入一次。

function add_path_to_array($path, $array) {
    $path = trim($path, '/');

    $exploded = explode('/',$path);
    if (count($exploded) > 1) {
        $key = $exploded[0];
        if (!isset($array[$key]))
            $array[$key] = array();
        $array[$key] = array_replace_recursive($array[$key], add_path_to_array(substr($path, strpos($path, '/')), $array[$key]));
    }
    else
        if (!in_array($path, $array))
            $array[] = $path;
    return $array;  
}
$list = array(
    '/a/b/aaaa.txt',
    '/c/d/bbbb.txt',
    '/a/z/dddd.txt',
    '/a/b/c/d/yyyy.txt',
);

$nested_array = array();

foreach($list as $path)
    $nested_array = add_path_to_array($path, $nested_array);

var_dump($nested_array);