展开创建多维数组的路径 [英] Explode path to create multidimensional array
本文介绍了展开创建多维数组的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从一个zip文件中创建一个关联数组,其中的文件夹是键,而文件是最里面的值.
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.
当前,当我在zip文件中的每个条目上按/
爆炸时,会得到类似以下内容:
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
)
要实现这一点(在$path
上执行print_r
):
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);
我想要的是$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?
推荐答案
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);
这篇关于展开创建多维数组的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文