Last active
April 14, 2022 12:44
-
-
Save sumitpore/4d10810bf4f7322a83a071ca7c6cbf04 to your computer and use it in GitHub Desktop.
Convert Zip Structure to Associative Array using PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Borrowed from https://stackoverflow.com/a/38407568/1994640 | |
* | |
* Fixed fatal errors and unwanted creation of empty arrays | |
*/ | |
$filePath = 'hello.zip'; | |
$za = new ZipArchive(); | |
if ($za->open($filePath) !== true) { // check for the zip archive | |
echo "archive doesn't exist or it's on Read-only mode "; | |
return; | |
} | |
$Tree = $pathArray = array(); //empty arrays | |
for ($i = 0; $i < $za->numFiles; $i++) { | |
$path = $za->getNameIndex($i); | |
$pathBySlash = array_values(explode('/', $path)); | |
$c = count($pathBySlash); | |
$temp = &$Tree; | |
for ($j = 0; $j < $c - 1; $j++){ | |
if (isset($temp[$pathBySlash[$j]])) | |
$temp = &$temp[$pathBySlash[$j]]; | |
else { | |
$temp[$pathBySlash[$j]] = array(); | |
$temp = &$temp[$pathBySlash[$j]]; | |
} | |
if (substr($path, -1) != '/') { | |
$temp[] = $pathBySlash[$c - 1]; | |
} | |
} | |
} | |
$za->close(); | |
echo "<pre>"; | |
print_r($Tree); | |
echo "</pre>"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment