gpt4 book ai didi

php - RecursiveIteratorIterator - 格式化数组

转载 作者:搜寻专家 更新时间:2023-10-31 21:09:57 26 4
gpt4 key购买 nike

我目前有一个网站可以显示所有目录和子目录(在 MAC 操作系统上)所以我这里有代码

$Directory = new RecursiveDirectoryIterator('/');
$Iterator = new RecursiveIteratorIterator($Directory);

foreach($Iterator as $name => $object){
echo "$name<br/>";
}

所以它会回显出目录的所有真实路径(目前在windows环境下工作)

C:\xampp\apache\bin
C:\xampp\apache\bin\.
C:\xampp\apache\bin\..
C:\xampp\apache\bin\ab.exe
C:\xampp\apache\bin\abs.exe
C:\myfolder\mysubfolder
C:\myfolder\mysubfolder\.
C:\myfolder\mysubfolder\..
C:\myfolder\mysubfolder\anotherfile.php
C:\myfolder\mysubfolder\another_folder
C:\myfolder\mysubfolder\another_folder\.
C:\myfolder\mysubfolder\another_folder\..
C:\myfolder\mysubfolder\another_folder\file.txt

我想做的是,显示在列表中所以像这样:

C:\
xampp\
apache\
bin\
ab.exe
abs.exe
myfolder\
mysubfolder\
anotherfile.php\
another_folder\
file.txt

是否可以像我上面放的那样格式化数组中的数据,而不是完整路径?我不确定如何使用“分解”并将它们分组到新数组中...?

你好,我试过这些代码:

foreach($objects as $name => $object){
$newname=explode('\\', $name);
print_r($newname);
}

它给了我:

array = { [0] => C:\
[1]=>xampp
[2]=>apache
[3]=>bin}

array = { [0] => C:\
[1]=>xampp
[2]=>apache
[3]=>bin
[4]-> . }

array = { [0] => C:\
[1]=>xampp
[2]=>apache
[3]=>bin
[4]=>.
[5]=>. . }

array = { [0] => C:\
[1]=>xampp
[2]=>apache
[3]=>bin
[4]=>ab.exe }

array = { [0] => C:\
[1]=>xampp
[2]=>apache
[3]=>bin
[4]=>abs.exe }

现在,我不确定如何循环播放它们以便它们在组中回显例如

xampp
apache
bin
ab.exe
abs.exe

谢谢

最佳答案

DirectoryIterator (+ 递归函数)可以为您做到这一点。

$resutl = RecursiveDirectoryIterator(new DirectoryIterator('/path/to/dir'));

function RecursiveDirectoryIterator(DirectoryIterator $path)
{
$data = array();
foreach ($path as $node){
if ($node->isDir() && !$node->isDot()){
$data[$node->getFilename()] = RecursiveDirectoryIterator(new DirectoryIterator($node->getPathname()));
}
elseif ($node->isFile()){
$data[] = $node->getFilename();
}
}
return $data;
}

关于php - RecursiveIteratorIterator - 格式化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22376724/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com