0

I got path list from recursive glob function... something like

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

What is the simplest way to put those into array:

$a[a][b][] = aaaa.txt
$a[c][d][] = bbbb.txt
$a[a][z][] = dddd.txt
$a[a][b][c][d][] = yyyy.txt
Flash Thunder
  • 11,672
  • 8
  • 47
  • 91

2 Answers2

1

This sounds like a homework exercise testing if you grasped the concept of recursion. Once you wrap your head around this concept, this kind of problem gets easy to solve.

$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);
Max
  • 6,563
  • 4
  • 25
  • 33
0

Fully recursive solution, I use it when I need to merge 2 glob arrays. All duplicates inserted only once.

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);
V G
  • 1,225
  • 9
  • 13