菜单

php遍历文件夹并存入数组

2010年06月18日 - php

<?php
$dir = dirname(__FILE__);
function read_dir_all($dir) {
$ret = array(‘dirs’=>array(), ‘files’=>array());
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if($file != ‘.’ && $file !== ‘..’) {
$cur_path = $dir . DIRECTORY_SEPARATOR . $file;
if(is_dir($cur_path)) {
$ret[‘dirs’][$cur_path] = read_dir_all($cur_path);
} else {
$ret[‘files’][] = $cur_path;
}
}
}
closedir($handle);
}
return $ret;
}

$p = read_dir_all($dir);
echo ‘<pre>’;
var_dump($p);
echo ‘</pre>’;
?>

优化版:

function read_dir_all($dir) {
$ret = array();
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if($file != ‘.’ && $file !== ‘..’) {
$cur_path = $dir . DIRECTORY_SEPARATOR . $file;
if(is_dir($cur_path)) {
$ret[$cur_path] = read_dir_all($cur_path);
} else {
$ret[$cur_path] = $cur_path;
}
}
}
closedir($handle);
}
return $ret;
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注