如何计算一个文件在多少个子目录中


how to count how many sub-directories a file is in?

我有一个名为count.php的文件。

这是存储count.php的地方(绝对路径):

/home/content/61/7475161/html/wordpress/project/folder1/folder2/folder3/folder4/count.php

我需要一种方法来计算路径中涉及文件夹project中的多少个子文件夹。

所以在上面的例子中,是四个。我想出了一个办法:

$pathtofile=dirname(__FILE__);
$path_array=explode("/",$pathtofile);
$f_stat=false;
$num_folders=0;
foreach ($path_array as $folder){
if($f_stat===false){
if($folder=="project"){$f_stat=true}
}//end of f_stat false
else{
$num_folders++;
}//end of else
}//end of foreach
//now $num_folders will equal 4 xD

我不认为这是最好的方法,所以任何建议都会很棒。谢谢

只需使用/project进行strstr,然后像这样计算爆炸后的数组元素:

$path_array=explode('/',strstr($pathtofile, '/project'));
$depth = count($path_array)-1;
echo (substr_count('/',$path) - 7); //> Subtract the number of main dir
 $dir=glob(directoryname."/*",GLOB_ONLYDIR);

$dir return an array,包含文件夹中的所有子文件夹。