Organize folders, subfolders and acquisitions of an array?

Asked

Viewed 407 times

2

Well, I have an array with the values:

array("Pasta/Readme.txt", "Pasta/Subpasta/helloworld.mp3", "Pasta-2/screenshot.png");

How to return an array like this:

array("Pasta" => array("Readme.txt", "Subpasta" => array("helloworld.mp3")), "Pasta-2" => array("screenshot.png"))

Thanks in advance :)

2 answers

1


Whereas you’ll always have that hierarchy: m folders with n files within each of them and no subfolder:

<?php

// vetor de arquivos
$arquivos = array(
    'Big Hero 6/Big Hero 6.avi',
    'Big Hero 6/readme.txt',
    'Big Hero 6 Screenshots/screenshot.png'
);

// vetor de arquivos divididos por pastas
$pastas = [];

// pegamos cada um dos arquivos e colocamos no array de subpastas,
// na pasta correspondente
for ($i=0, $count=sizeof($arquivos); $i<$count; $i++) {
    list($pasta, $arquivo) = explode('/', $arquivos[$i]);
    if (!isset($pastas[$pasta])) {
        $pastas[$pasta] = [];
    }
    $pastas[$pasta][] = $arquivo;
}

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.