0

Is there any library or plugin that I can use to easily convert a list of filenames into a filetree ?

Say for example I have an array that contains a list of file names that I read from text:

C\Folder1\Flower.jpg
C\Folder1\Monkey.jpg
C\Folder1\Hello.jpg
C\Folder2\Binkie.txt
C\Folder2\Spike.png
C\Folder3\Django.jpg
C\Folder3\Tessje.tiff

How can I display the list of filenames above in filetree ? Most of the filetree plugins I've seen requires either a real files and folders structure or are very complicated to understand.

Rafik Bari
  • 4,867
  • 18
  • 73
  • 123

1 Answers1

1

if you have array like this:

array(
    'c' => array(
        'Folder1' => array(
            'Flower.jpg',
            'Monkey.jpg',
            ...
        ),
        'Folder2' => array(
            'Binkie.txt',
            ...
        ),
    ),
),

you can use recursive function:

<?php

$arr = array(
    'c' => array(
        'Folder1' => array(
            'Flower.jpg',
            'Monkey.jpg',
            //...
        ),
        'Folder2' => array(
            'Binkie.txt',
            //...
        ),
    ),
);

function drawTree($container, $nesting = 0)
{
    foreach ($container as $folder => $sub) {
        if (is_array($sub)) {
            echo str_repeat('.', $nesting) . $folder . '<br>';

            drawTree($sub, $nesting + 1);
        } else {
            echo str_repeat('.', $nesting) . $sub . '<br>';
        }
    }
}

drawTree($arr);

for convert pathes to array tree, use this:

$arr = array(
    'C/Folder1/Flower.jpg',
    'C/Folder1/Monkey.jpg',
    'C/Folder1/Hello.jpg',
    'C/Folder2/Binkie.txt',
    'C/Folder2/Spike.png',
    'C/Folder3/Django.jpg',
    'C/Folder3/Tessje.tiff',
);

$result = array();

foreach ($arr as $file) {
    $exp = explode('/', $file);
    $curr = &$result;

    while (true) {
        $chunk = array_shift($exp);

        if (empty($exp)) {
            $curr[] = $chunk;
            break;
        }

        if (!isset($curr[$chunk])) {
            $curr[$chunk] = array();
        }
        $curr = &$curr[$chunk];
    }
}

var_dump($result);
deniskoronets
  • 520
  • 3
  • 15