2

I have the following list of paths

  • GRUPA131/LFA & others/lfa sub.zip
  • GRUPA131/LFA & others/lfandrei.pdf
  • GRUPA131/Limbaje formale (Liviu Dinu).pdf
  • GRUPA131/desktop.ini
  • GRUPA131/lfa/lab1/1-Theodors MacBook Air.cc
  • GRUPA131/lfa/lab1/1.cc
  • GRUPA131/lfa/lab1/1.cc-Theodors MacBook Air.out
  • GRUPA131/lfa/lab1/1.cc.out
  • GRUPA131/lfa/lab1/2.cc
  • GRUPA131/lfa/lab1/input3.in
  • GRUPA131/lfa/lab1/tema1.zip
  • alexandru-lamba.png
  • alexandru-lamba_v2.png
  • analiza carte 1.pdf
  • analiza carte 2.pdf
  • biblsit.docx
  • center.js

as strings and I want to convert them into a folder hierarchy representable with HMTL. So, for each folder, I want to list it's files, and subfolders, and so on until the list is finished.

It would be best to have the php array hierarchy as follows:

  $dirs['dirname'] -> file 1
  $dirs['dirname'] -> file 2
  $dirs['dirname'] -> file 3
  $dirs['dirname'] -> Folder
  $dirs['dirname']['folder'] -> file 1
  $dirs['dirname']['folder'] -> file 2..

I have tried to split each string by '/' ( PATH_DELIMITER ) but I cannot figure out how to actually get an array like I have mentioned earlier.

Also, my array that has the entire paths, is a simple array. Not associative or so.

Can someone help me figure out how to do this?

Thanks!

roshkattu
  • 241
  • 6
  • 22

1 Answers1

5

Easiest way will be recursive function. My proposal:

function build_folder_structure(&$dirs, $path_array) {
    if (count($path_array) > 1) {
        if (!isset($dirs[$path_array[0]])) {
            $dirs[$path_array[0]] = array();
        }

        build_folder_structure($dirs[$path_array[0]], array_splice($path_array, 1));
    } else {
        $dirs[] = $path_array[0];
    }
}

$strings = array(
    'GRUPA131/LFA & others/lfa sub.zip',
    'GRUPA131/LFA & others/lfandrei.pdf',
    'GRUPA131/Limbaje formale (Liviu Dinu).pdf',
    'GRUPA131/desktop.ini',
    'GRUPA131/lfa/lab1/1-Theodors MacBook Air.cc',
    'GRUPA131/lfa/lab1/1.cc',
    'GRUPA131/lfa/lab1/1.cc-Theodors MacBook Air.out',
    'GRUPA131/lfa/lab1/1.cc.out',
    'GRUPA131/lfa/lab1/2.cc',
    'GRUPA131/lfa/lab1/input3.in',
    'GRUPA131/lfa/lab1/tema1.zip',
    'alexandru-lamba.png',
    'alexandru-lamba_v2.png',
    'analiza carte 1.pdf',
    'analiza carte 2.pdf',
    'biblsit.docx',
    'center.js'
);

$dirs = array();

foreach ($strings As $string) {
    $path_array = explode('/',$string);

    build_folder_structure($dirs,$path_array);
}

print_r($dirs);

Check:

What is a RECURSIVE Function in PHP?

http://php.net/manual/en/language.references.pass.php

Community
  • 1
  • 1
Arius
  • 1,387
  • 1
  • 11
  • 24