Explode path to create multidimensional array

2020-03-06 04:15发布

问题:

I am trying to make an associative array from a zip file, where the folders are the keys and the files are the innermost values.

Currently when I explode on / on each entry in the zip file I get something like this:

Array
(
    [0] => Folder1
    [1] => Folder2
    [2] => File1.txt
)
Array
(
    [0] => Folder1
    [1] => Folder2
    [2] => File2.txt
)
Array
(
    [0] => Folder1
    [1] => Folder3
    [2] => File3.txt
)

To achieve that I am doing this (doing a print_r on $path):

if(in_array($content["ext"], array("zip"))){
    $zip       = zip_open($file);
    while($zip_entry = zip_read($zip)){
        $zip_path    = zip_entry_name($zip_entry);
        $path        = explode("/", $zip_path);
        $path        = array_filter($path);
        $lastElement = end($path);

        foreach($path as $key => $item){
            if($item != $lastElement){

            }
        }
    }
}

print_r($files);

What I would like is for $files to contain a multidimensional array for a result that looks like this:

Array
(
    [Folder1] => Array
    (
        [Folder2] => Array
        (
            [0] => File1.txt
            [1] => File2.txt
        )
        [Folder3] => Array
        (
            [0] => File3.txt
        )
    )
)

What is the best way to achieve this without a depth?

回答1:

if (in_array($content["ext"], array("zip"))) {
    $zip = zip_open($file);

    $files = array();

    while ($zip_entry = zip_read($zip)) {
        $zip_path = zip_entry_name($zip_entry);
        $path = explode("/", $zip_path);
        $path = array_filter($path);
        $lastElement = end($path);

        //reset pointer
        $cur = &$files;

        $count = count($path);

        //set pointer to proper parent folder
        for ($i = 0; $i < $count - 1; $i++) {
            $cur = &$cur[$path[$i]];
        }

        //add file
        $cur[] = $path[$i];
    }

    //delete pointer
    unset($cur);
}

print_r($files);


回答2:

You might be able to explode the path on the / and then use a forloop to put all parts inside a other array.

Then you can add an if(...) check if the current folder or file is already in the Array. if that is true, you continue, else you add it to the array and then continue