本站资源收集于互联网,不提供软件存储服务,每天免费更新优质的软件以及学习资源!

PHP无限极数组如何映射成文件夹结构?

网络教程 app 1℃

PHP无限极数组如何映射成文件夹结构

使用 php 将无限极数组映射成文件夹

在处理配置文件时,经常需要将嵌套的数组映射成文件和目录结构。例如,给定以下配置文件:

$config = [ ‘uuid’=>’string’, ‘info’=>’string’, ‘main’=>[ ‘uuid’=>’string’, ‘cmd’=>’string’, ‘child’=>[‘uuid’=>’string’,’remark’=>’string’,’game’=>[ ‘user’=>’name’, ‘money’=>’1000’] ], ‘logs’=>[‘path’=>’/path/path’,’date’=>’2023-09-01′ ] ], ‘video’=>[ ‘uuid’=>’vid’, ‘info’=>’info’, ‘file’=>[‘size’=>’12900’ ] ]];

需要将其映射成如下目录结构:

mainmain/childmain/child/gamemain/logsvideovideo/file

为了解决这个问题,可以使用如下的 php 代码将无限极数组映射成文件夹:

function flatten($nodes, $prefix = ”) { $list = []; foreach ($nodes as $key => $value) { if (is_array($value)) {$path = $prefix . $key;$list[] = $path;$list = array_merge($list, flatten($value, $path . ‘/’)); } } return $list;}$list = flatten($config);

或者使用 recursiveiteratoriterator:

$list = [];$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($config), RecursiveIteratorIterator::SELF_FIRST);foreach ($iterator as $key => $value) { if (is_array($value)) { $path = ”; foreach (range(0, $iterator->getDepth()) as $depth) {$path .= $iterator->getSubIterator($depth)->key() . ‘/’; } $list[] = rtrim($path, ‘/’); }}

以上就是PHP无限极数组如何映射成文件夹结构?的详细内容,更多请关注范的资源库其它相关文章!

转载请注明:范的资源库 » PHP无限极数组如何映射成文件夹结构?

喜欢 (0)