PHP:如何在数组中填充目录结构 [英] PHP: How to populate a directory structure in an array

查看:91
本文介绍了PHP:如何在数组中填充目录结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个管理面板,该面板显示服务器上特定位置的目录结构.我有一个递归的php函数,它遍历每个文件和文件夹.我不知道如何将这个目录结构存储在这样的php关联数组中:

I am developing an admin panel that shows the directory structure of a specific location on server. I have got a recursive php function that iterates through every file and folder there is. What I can't figure out is how can I store this directory structure in a php associative array like this:

array[foldername1][0]=file; // if the foldername1 contains a file
array[foldername1][foldername2][0]=file //if foldername1 contains another folder(foldername2) along with the file.

我要遵循的规则是;文件夹应始终是键,文件应始终在这样的索引处:

The rule i am trying to follow is; a folder should always be a key and file should always be at an index like this:

array[folder1][folder2][0]=file1;
array[folder1][folder2][1]=file2;

用于填充此关联数组的函数应该是通用的,因为我们永远不知道目录结构可以是什么.我想将这个数组json_encode回到我的客户端,并使用javascript处理它,目前还没有问题.

The function to populate this associative array should be generic as we never know what the directory structure can be. I want to json_encode this array back to my client and deal with it in javascript which is not a problem at the moment.

如果这是一个不好的方法,请告诉我,也许有更好的方法可以做到这一点.我曾想过使用平面阵列,但我认为它是一个糟糕的设计.

If this is a bad approach please let me know cauze there might be a better way to do this. I thought of using a flat array but i guess its a bad design.

推荐答案

$ritit = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__), RecursiveIteratorIterator::CHILD_FIRST);
$r = array();
foreach ($ritit as $splFileInfo) {
   $path = $splFileInfo->isDir()
         ? array($splFileInfo->getFilename() => array())
         : array($splFileInfo->getFilename());

   for ($depth = $ritit->getDepth() - 1; $depth >= 0; $depth--) {
       $path = array($ritit->getSubIterator($depth)->current()->getFilename() => $path);
   }
   $r = array_merge_recursive($r, $path);
}

print_r($r);

这篇关于PHP:如何在数组中填充目录结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆