使用 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' ] ] ];
需要将其映射成如下目录结构:
main main/child main/child/game main/logs video video/file
为了解决这个问题,可以使用如下的 php 代码将无限极数组映射成文件夹:
立即学习“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, '/'); } }