取得目录数据形成一定的结构
使用多维数组的嵌套,表示层级关系!
将目录关系存放到数组中.
例如:
array(
array('filename'=>'index.php','type'=>'file'),
array('filename'=>'applicttion','type'=>'dir','nested'=>array(
array('filename'=>'.htacces','type'='file'),
array('filename'=>'back','type'=>'dir','nested'=>array(
...
)
),
)
)
...
)
<?php
$path = "../shop2018";
$list = readDirsNested($path);
echo "<pre>";
print_r($list);
// foreach($list as $first_key=>$first) {
// echo $first_key, $first['name'], '<br>';
// if ($first['type'] == 'file') continue;
// foreach($first['nested'] as $second_key => $second) {
// echo ' ', $first_key , 'nested' , $second_key, $second['name'], '<br>';
// }
// }
function readDirsNested($path) {
//存放所有目录内容
$nested = array();
//打开目录
$path_handle = opendir($path);
//循环读取
while(false !== $file = readdir($path_handle)){
//排除隐含目录 . 和 ..
if( $file == '.' || $file == '..' )continue;
//创建当前文件信息
$fileinfo = array();
$fileinfo['name'] = $file;
//转成utf8,应对目录/文件名字中文乱码
//$fileinfo['name'] = iconv('GB18030', 'UTF-8', $file);
//判断是否是目录
if( is_dir( $path . '/' . $file ) ){
//是目录
//$fileinfo['filename'] = $file;
$fileinfo['type'] = 'dir';
$fun = __FUNCTION__;
$fileinfo['nested'] = $fun($path.'/'.$file);
}else{
//是文件
//$fileinfo['filename'] = $file;
$fileinfo['type'] = 'file';
}
$nested[] = $fileinfo;
}
closedir($path_handle);
return $nested;
}
----------
结果
-----------
Array
(
[0] => Array
(
[name] => application
[type] => dir
[nested] => Array
(
[0] => Array
(
[name] => back
[type] => dir
[nested] => Array
(
)
)
[1] => Array
(
[name] => config
...