gpt4 book ai didi

PHP递归目录路径

转载 作者:可可西里 更新时间:2023-11-01 12:26:51 25 4
gpt4 key购买 nike

我有这个函数来返回完整的目录树:

function getDirectory( $path = '.', $level = 0 ){

$ignore = array( 'cgi-bin', '.', '..' );
// Directories to ignore when listing output. Many hosts
// will deny PHP access to the cgi-bin.

$dh = @opendir( $path );
// Open the directory to the handle $dh

while( false !== ( $file = readdir( $dh ) ) ){
// Loop through the directory

if( !in_array( $file, $ignore ) ){
// Check that this file is not to be ignored

$spaces = str_repeat( ' ', ( $level * 4 ) );
// Just to add spacing to the list, to better
// show the directory tree.

if( is_dir( "$path/$file" ) ){
// Its a directory, so we need to keep reading down...

echo "<strong>$spaces $file</strong><br />";
getDirectory( "$path/$file", ($level+1) );
// Re-call this same function but on a new directory.
// this is what makes function recursive.

} else {

echo "$spaces $file<br />";
// Just print out the filename

}

}

}

closedir( $dh );
// Close the directory handle

}

但我想做的是搜索一个文件/文件夹并返回它的路径,我该怎么做?你有这样的功能吗?或者你能给我一些关于如何做到这一点的提示吗?

最佳答案

尝试使用RecursiveIteratorIterator结合RecursiveDirectoryIterator

$path = realpath('/path/you/want/to/search/in');

$objects = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::SELF_FIRST);

foreach($objects as $name => $object){
if($object->getFilename() === 'work.txt') {
echo $object->getPathname();
}
}

补充阅读:

关于PHP递归目录路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2398147/

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