Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sumitpore/4d10810bf4f7322a83a071ca7c6cbf04 to your computer and use it in GitHub Desktop.
Save sumitpore/4d10810bf4f7322a83a071ca7c6cbf04 to your computer and use it in GitHub Desktop.
Convert Zip Structure to Associative Array using PHP
<?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