您只能使用glob()。
在您描述的确切情况下,它应该如下所示:
$files = glob('path_to_images/*/FILE.jpg');
更一般地说,在已知文件夹路径和搜索到的文件名之间放置任意数量的/* 以探索给定的深度级别。
编辑,根据 OP 的评论扩展解决方案
如果你对树结构一无所知,你可以做一个深度的多级搜索,像这样:
function doGlob($target, $context) {
if ($dirs = glob($context . '/*', GLOB_ONLYDIR)) {
foreach ($dirs as $dir) {
$result = array_merge($result, doGlob($target, $dir));
}
}
return $result;
}
$files = doGlob('FILE.jpg', 'path_to_images');
它将返回给定$context 中任何位置出现的所有$target 文件。
注意:如果context 是一个大结构,可能会很耗时!
所以你可能会限制搜索深度,像这样:
function doGlob($target, $context, $max_depth = -1, $depth = 0) {
$result = glob($context . '/' . $target);
if ($depth > $max_depth) {
return $result;
}
if ($dirs = glob($context . '/*', GLOB_ONLYDIR)) {
foreach ($dirs as $dir) {
$result = array_merge($result, doGlob($target, $dir, $max_depth, $depth + 1));
}
}
return $result;
}
$files = doGlob('FILE.jpg', 'path_to_images', <max-depth>);
另一方面,如果您打算只检索一个唯一的文件,您可能更简单地在找到它后立即停止:
function doGlob($target, $context) {
if ($result) {
return $result;
}
if ($dirs = glob($context . '/*', GLOB_ONLYDIR)) {
foreach ($dirs as $dir) {
$result = array_merge($result, doGlob($target, $dir));
}
}
return $result;
}
$files = doGlob('FILE.jpg', 'path_to_images');