我怎样才能保存目录树到PHP中的数组? [英] How can I save a directory tree to an array in PHP?
问题描述
top
folder1
file1
folder2
file1
file2
将其保存到数组中例如:
$ p $ array
(
'folder1'=> array('file1'),
'folder2'=>数组('file1','file2')
)
通过这种方式,我可以轻松地在我的网站中重新使用树。我一直在玩这个代码,但它仍然没有做我想要的:
private function get_tree()
{
$ uploads = __RELPATH__。 DS。 '上市' 。 DS。 上传;
$ iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($ uploads),RecursiveIteratorIterator :: SELF_FIRST);
$ output = array();
$ b foreach($ iterator as $ file)
{
$ relativePath = str_replace($ uploads。DS,'',$ file); ($!
$ b $ if($ file-> isDir())
{
if(!in_array($ relativePath,$ output))
$ output [$ relativePath] = array();
}
}
return $ output;
但是我设法想出了这个..不知道这是你正在寻找什么
$ $ p $ $ code function tree($ path,$顶部){
$ ignore = array('cgi-bin','。','..');
$ handle = opendir($ path); ($ file = readdir($ handle))!== false){
if(!in_array($ file,$ ignore)){
if(is_dir($ path / $ file)){
$ top [$ file] = @ tree($ path / $ file,$ top [$ file]);
} else {
$ top [] = $ file;
}
}
}
closedir($ handle);
返回$ top;假设你的目录树是
$ b
假设你的目录树是
输出
数组
(
[a] =>数组
(
[ aa] => Array
(
[0] => aa.txt
)
)
[b] = >数组
(
[0] => bb.txt
)
[c] =>数组
(
[0] => cc.txt
)
)
<但是,休息一下,观看每300年发生一次的日食。当你的孩子,孙辈,曾祖父问你你知道你在冬至日食发生时还活着吗?时,你不想说不你看到了吗?
:)
I'm trying to take a directory with the structure:
top
folder1
file1
folder2
file1
file2
And save it into an array like:
array
(
'folder1' => array('file1'),
'folder2' => array('file1', 'file2')
)
This way, I can easily resuse the tree throughout my site. I've been playing around with this code but it's still not doing what I want:
private function get_tree()
{
$uploads = __RELPATH__ . DS . 'public' . DS . 'uploads';
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($uploads), RecursiveIteratorIterator::SELF_FIRST);
$output = array();
foreach($iterator as $file)
{
$relativePath = str_replace($uploads . DS, '', $file);
if ($file->isDir())
{
if (!in_array($relativePath, $output))
$output[$relativePath] = array();
}
}
return $output;
}
Im horrible with recursive functions. But i managed to come up with this..not sure it's what you're looking for
function tree($path, $top) {
$ignore = array('cgi-bin', '.', '..' );
$handle = opendir($path);
while( ($file = readdir($handle)) !== false ) {
if( !in_array( $file, $ignore ) ){
if( is_dir("$path/$file") ) {
$top[$file] = @ tree("$path/$file", $top[$file]);
} else {
$top[] = $file;
}
}
}
closedir( $handle );
return $top;
}
Assuming your directory tree is
it outputs
Array
(
[a] => Array
(
[aa] => Array
(
[0] => aa.txt
)
)
[b] => Array
(
[0] => bb.txt
)
[c] => Array
(
[0] => cc.txt
)
)
But, take a break and go watch the eclipse that happens every 300 and something years. You dont want to say 'no' when your kids, grandkids, great-grandkids ask you 'did you know you were alive when the winter solstice eclipse occurred?? did you see it?????"
:)
这篇关于我怎样才能保存目录树到PHP中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!