List folder and subfolders in a PHP foreach

Asked

Viewed 1,093 times

2

I’m using the library Comic to extract information from a file .torrent, the idea and lists the information of the torrent files in a table using the foreach, however during listing, files that are inside a directory do not appear as they should, only the path to the file appears.

  • The library Comic centralizes file and folder information into one array multidimensional.
  • I removed the classes to shorten the code.

  • I’ll leave the project’s source on github for those who want to take a closer look.

As appears: inserir a descrição da imagem aqui

How could you leave it so, making the files follow the directory and the subdirectories:

inserir a descrição da imagem aqui

Display the first folder and list the files inside, so on.

<table>
    <thead>
        <tr>
            <th scope='col'>ARQUIVOS</th>
            <th scope='col'>TAMANHO</th>
        </tr>
    </thead>
<tbody>
<?php if(isset($torrent->result['info']['files'])) {
    foreach($torrent->result['info']['files'] as $file) {
    echo "<tr><td>
    <a>".extension(implode('\\',$file['path']))."</a>".implode('\\',$file['path'])."</td>
    <td>".$file['length'])."</td></tr>";
    } ?>
    <?php } else { 
    echo "<tr><td>".$torrent->result['info']['name']."</td>
    <td>".$torrent->result['info']['length']."</td></tr>";
    } ?>
</tbody>
</table>

1 answer

3


I created these scripts to run result of BDECODE and create an array, maybe one of these options will help you. = D


This option creates an array where the key is the file path.

require_once 'BDecode.php';
$tor = new BDECODE('file.torrent');

$dir = [];
foreach( $tor->result['info']['files'] as $file ){
    $filename = array_pop($file['path'] );

    /// key inicial 
    $key = "/"; 

    /// gera a $key baseado no path
    if( count($file['path']) ) 
        $key .= implode("/",$file['path']);

    /// cria $key na array caso não exista
    if( !isset($dir[$key]) ) $dir[$key] = [];

    /// adiciona um novo arquivo na $key
    array_push($dir[$key],$filename);
    /// array_push($dir[$key], [ $filename, $file['length'] ] );
}

Exit:

Array
(
    [/] => Array
        (
            [0] => [rvarun7777 rips] Follow me if you like my encodes!!!!!.txt
            [1] => Customized Folder View 1.PNG
            [2] => Customized Folder View.PNG
        )

    [/Extras/[Spoiler] Alternate Ending [Official]] => Array
        (
            [0] => Breaking Bad' Alternate Ending Is a Dream Come True _rvarun7777.mp4
        )

    [/Extras] => Array
        (
            [0] => Box Set Cover 2.jpg
            [1] => Box Set Cover.jpg
        )

    [/Extras/Breaking Bad Memes] => Array
        (
            [0] => Breaking Bad Memes_rvarun7777 (1).jpg
            [1] => Breaking Bad Memes_rvarun7777 (2).jpg
            [2] => Breaking Bad Memes_rvarun7777 (3).jpg
            [3] => Breaking Bad Memes_rvarun7777 (4).jpg
            [4] => Breaking Bad Memes_rvarun7777 (5).jpg
            [5] => Breaking Bad Memes_rvarun7777 (6).jpg
            [6] => Breaking Bad Memes_rvarun7777 (7).jpg
            [7] => Breaking Bad Memes_rvarun7777 (8).jpg
        )

...

This option creates an array of arrays.
Attempt to simulate a directory. = P

require_once 'BDecode.php';
$tor = new BDECODE('file.torrent');

function recursiveDir($path,&$dirbase ){

    if( count($path) > 1 )
    {
        /// criar diretorio com o nome
        $dirname = array_shift($path);
        if( !isset($dirbase[ $dirname ]) ) $dirbase[ $dirname ] = []; /// criar o diretorio caso nao exista
        recursiveDir( $path, $dirbase[ $dirname ] );  /// chama novamente para criar subdirs, e adicionar arquivos
    }
    else
    {
        /// pode se criar uma key ( Ex.: '.' ou 'files' ) ou apenas array_push no arquivo
        /// array_push( $dirbase, array_shift($path) );
        if( !isset($dirbase['.']) ) $dirbase['.'] = [];
        array_push( $dirbase['.'], array_shift($path) ); // guarda o arquivo na array de key '.'
    }
}

$dir = [];
foreach( $tor->result['info']['files'] as $file ){
    recursiveDir( $file['path'] , $dir );
}

print_r($dir);

Exit:

Array
(
    [.] => Array
        (
            [0] => [rvarun7777 rips] Follow me if you like my encodes!!!!!.txt
            [1] => Customized Folder View 1.PNG
            [2] => Customized Folder View.PNG
        )

    [Extras] => Array
        (
            [[Spoiler] Alternate Ending [Official]] => Array
                (
                    [.] => Array
                        (
                            [0] => Breaking Bad' Alternate Ending Is a Dream Come True _rvarun7777.mp4
                        )

                )

            [.] => Array
                (
                    [0] => Box Set Cover 2.jpg
                    [1] => Box Set Cover.jpg
                )

            [Breaking Bad Memes] => Array
                (
                    [.] => Array
                        (
                            [0] => Breaking Bad Memes_rvarun7777 (1).jpg
                            [1] => Breaking Bad Memes_rvarun7777 (2).jpg
                            [2] => Breaking Bad Memes_rvarun7777 (3).jpg
                            [3] => Breaking Bad Memes_rvarun7777 (4).jpg
                            [4] => Breaking Bad Memes_rvarun7777 (5).jpg
                            [5] => Breaking Bad Memes_rvarun7777 (6).jpg
                            [6] => Breaking Bad Memes_rvarun7777 (7).jpg
                            [7] => Breaking Bad Memes_rvarun7777 (8).jpg
                        )

                )
...

Note that the key '.' is the list of files in the folder, all other Keys are subdirectories.


A variation of the second option, if you want the $file['length'] along with the file you can change some lines and instead of '.' be a list of files it turn into a list of [ arquivo, length ]

Thus remaining:

require_once 'BDecode.php';
$tor = new BDECODE('file.torrent');

function recursiveDir($path,&$dirbase,$length ){
///                                      ^
///                                    mudei aki    
    if( count($path) > 1 )
    {
        /// criar diretorio com o nome
        $dirname = array_shift($path);
        if( !isset($dirbase[ $dirname ]) ) $dirbase[ $dirname ] = []; /// criar o diretorio caso nao exista
        recursiveDir( $path, $dirbase[ $dirname ], $length );  /// chama novamente para criar subdirs, e adicionar arquivos
        //                                             ^
        //                                            mudei aqui
    }
    else
    {
        /// pode se criar uma key ( Ex.: '.' ou 'files' ) ou apenas array_push no arquivo
        /// array_push( $dirbase, array_shift($path) );
        if( !isset($dirbase['.']) ) $dirbase['.'] = [];
        array_push( $dirbase['.'], [array_shift($path), $length] ); // guarda o arquivo na array de key '.'
        //                                        ^
        //                                      mudei aki, virou array de arquivo, length
    }
}

$dir = [];
foreach( $tor->result['info']['files'] as $file ){
    recursiveDir( $file['path'] , $dir , $file['length'] );
    //                                        ^
    //                                      mudei aki
}

The output of this would be +/- like this:

Array
(
    [.] => Array
        (
            [0] => Array
                (
                    [0] => [rvarun7777 rips] Follow me if you like my encodes!!!!!.txt
                    [1] => 521
                )

            [1] => Array
                (
                    [0] => Customized Folder View 1.PNG
                    [1] => 752619
                )

            [2] => Array
                (
                    [0] => Customized Folder View.PNG
                    [1] => 938548
                )

        )

    [Extras] => Array
        (
            [[Spoiler] Alternate Ending [Official]] => Array
                (
                    [.] => Array
                        (
                            [0] => Array
                                (
                                    [0] => Breaking Bad' Alternate Ending Is a Dream Come True _rvarun7777.mp4
                                    [1] => 43890886
                                )

                        )

                )
...
  • 1

    It worked perfectly, thanks for the help and the explanation.

Browser other questions tagged

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