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' ] ] ]; 以上是配置文件的一部分:现在需要根据配置生成目录,`只考虑键值为数组的情况`键值字符串是文件的属性。 $list = [ 'main', 'main/child', 'main/child/game', 'main/logs', 'video', 'video/file', ... ]; 我考虑`扁平化`,`new RecursiveIteratorIterator(new RecursiveArrayIterator($sqlite));` `foreach 递归` 都没弄成功。请求高手给解!

阅读量:271

点赞量:10

问AI
好久没写 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; } flatten($config); "image.png" (https://wmprod.oss-cn-shanghai.aliyuncs.com/images/20250113/e9d2b9e326b3eb529334e444a5c4d0da.png) *** 用 RecursiveIteratorIterator 也行,但需要指定第二个参数 "RecursiveIteratorIterator::SELF_FIRST": $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, '/'); } } "image.png" (https://wmprod.oss-cn-shanghai.aliyuncs.com/images/20250113/2c20a879703319248cf72587bebc52bc.png)