How to create a sub-directory tree with an Array

0

I have a path: C:\Users\Default\AppData\Local

I want a function that takes a path equal the path above and return an Array:

Output:

array(5) {
  [0]=> string(30) "C:\Users\Default\AppData\Local"
  [1]=> string(24) "C:\Users\Default\AppData"
  [2]=> string(16) "C:\Users\Default"
  [3]=> string(8) "C:\Users"
  [4]=> string(2) "C:"
}
    
asked by anonymous 05.07.2015 / 21:33

2 answers

2

Here you have:

function toArray($path) {
    $array = [$path];
    do {
        $path = pathinfo($path)['dirname'];
        $array [] = $path;
    } while (strlen(basename($path)) > 1);
    return $array;
}
var_dump(toArray("C:\Users\Default\AppData\Local"));

return will be:

array(5) { [0]=> string(30) "C:\Users\Default\AppData\Local" [1]=> string(24) "C:\Users\Default\AppData" [2]=> string(16) "C:\Users\Default" [3]=> string(8) "C:\Users" [4]=> string(3) "C:\" }

I will end with the indication that because I do not know if you use windows or linux I used the pathinfo function of php that will work in either case.

Update:

I found after answering that you can improve the function by checking for example if the directory exists and only if it exists and even a directory is that the function returns an array , otherwise returns false .

function toArray($path) {
    if (is_dir($path)) {
        $array = [$path];
        do {
            $path = pathinfo($path)['dirname'];
            $array [] = $path;
        } while (strlen(basename($path)) > 1);
        return $array;
    }
    return false;
}

$arr = toArray("C:\Users\Default\AppData\Local");
if ($arr) {
    var_dump($arr);
} else {
    echo "ups... o directório não existe ou não se identifica como tal.";
}
    
05.07.2015 / 22:24
0

I wrote a recursive function scandir :

dir_to_array.php

<?php

/**
 * Recebe uma pasta e escreve um array na mesma estrutura.
 *
 * @param   $dir
 * @param   array   $final
 * @return  array
 */
function dirsToArray($dir, &$final = [])
{
    $pastas = scandir($dir);

    if(empty($final))
        $final[] = $dir;

    foreach($pastas as $pasta)
    {
        if($pasta != '.' && $pasta != '..')
        {
            if(is_dir($dir . DIRECTORY_SEPARATOR . $pasta))
            {
                $final[] = $dir . DIRECTORY_SEPARATOR . $pasta;
                dirsToArray($dir . DIRECTORY_SEPARATOR . $pasta, $final);
            }
        }
    }

    return array_reverse($final);
}

die( print_r(dirsToArray('diretorio'), true) );

Output

Array
(
    [0] => diretorio\pasta2\subpasta3
    [1] => diretorio\pasta2\subpasta2\subpasta1
    [2] => diretorio\pasta2\subpasta2
    [3] => diretorio\pasta2\subpasta1\subpasta1
    [4] => diretorio\pasta2\subpasta1
    [5] => diretorio\pasta2
    [6] => diretorio\pasta1\subpasta2
    [7] => diretorio\pasta1\subpasta1\subpasta1
    [8] => diretorio\pasta1\subpasta1
    [9] => diretorio\pasta1
    [10] => diretorio
)

Warning : max_execution_time can pop.

    
05.07.2015 / 22:25