我的任务应该很简单,
less
文件夹。less
替换为css
所以,鉴于这种结构
注意:以下所有项目除 randomfile 外都是目录
matthew@vaio:/var/www/constructor/public/bundles$ tree
.
├── first
│ └── less
│ ├── secondtester
│ └── tester
│ ├── anothersubtester
│ ├── randomfile
│ └── subtester
├── second
│ └── less
│ ├── secondtester
│ └── tester
│ ├── anothersubtester
│ ├── randomfile
│ └── subtester
└── third
└── noless
├── secondtester
└── tester
├── anothersubtester
├── randomfile
└── subtester
18 directories, 3 files
我想最终得到这个数组(注意我在这里截断了路径只是为了让它更容易阅读)
Array
(
[/b/second/less] => /b/second/css
[/b/second/less/secondtester] => /b/second/css/secondtester
[/b/second/less/tester] => /b/second/css/tester
[/b/second/less/tester/subtester] => /b/second/css/tester/subtester
[/b/second/less/tester/anothersubtester] => /b/second/css/tester/anothersubtester
[/b/first/less] => /b/first/css
[/b/first/less/secondtester] => /b/first/css/secondtester
[/b/first/less/tester] => /b/first/css/tester
[/b/first/less/tester/subtester] => /b/first/css/tester/subtester
[/b/first/less/tester/anothersubtester] => /b/first/css/tester/anothersubtester
)
现在我有以下代码,但我认为这根本没有优化,例如我知道有RecursiveIteratorIterators
等,但我无法弄清楚如何将它们用于此任务,因此不得不求助于递归功能。基本上,我想知道如何写这个以更好地进行优化:
$directories = array();
$bundlePath = realpath('/public/bundles');
function lessSearcher($lessPath, $cssPath){
$directories = array($lessPath => $cssPath);
$lessDirs = new DirectoryIterator($lessPath);
foreach ($lessDirs as $lessDir) {
//we only want the directories and not the .'s
if ($lessDir->isDot() || !$lessDir->isDir()) continue;
$lessCurrent = $lessPath . '/' . $lessDir->getFileName();
$cssCurrent = $cssPath . '/' . $lessDir->getFileName();
$directories[$lessCurrent] = $cssCurrent;
$directories = array_merge($directories, lessSearcher($lessCurrent, $cssCurrent));
}
return $directories;
}
$bundles = new DirectoryIterator($bundlePath);
foreach ($bundles as $bundle) {
//we only want the directories and not the .'s
if($bundle->isDot() || !$bundle->isDir()) continue;
//we only want the directories that have a less directory
if(!realpath($bundlePath.'/'.$bundle->getFileName().'/less')) continue;
$lessPath = realpath($bundlePath . '/' . $bundle->getFileName()) . '/less';
$cssPath = realpath($bundlePath . '/' . $bundle->getFileName()) . '/css';
$directories = array_merge($directories, lessSearcher($lessPath, $cssPath));
}
答案 0 :(得分:0)
我认为代码已正确优化
我创建了一个列出所有目录和子目录的脚本,然后删除那些没有'less'目录的脚本,并为拥有它的那些创建一个新数组。
然后我用1000次循环测试你和我的。您的脚本平均 0.93s ,我的脚本采用 1.27s 。所以在我看来,你的代码还可以。
答案 1 :(得分:0)
我必须说,如果它足够快并完成工作,那么我会说没有必要进一步优化。如果你达到一个不够快或不能完成工作的点,那么就将其复活。无论如何,递归迭代器不太可能与您的实现有很大的不同。
对不起,我帮不了多忙。