Sorting files per directory using SPL's DirectoryTreeIterator

我们两清 提交于 2019-12-03 23:16:07

Well, I'm not sure where you got that class from, but it's doing some pretty messed up things (including a few bugs to say the least). And while it uses SPL, it's not an SPL class.

Now, I'm not 100% sure what you mean by "sort", but assuming you're talking about a natural sort, why not just flatten an array, and then sort it?

$it = new RecursiveTreeIterator(
    new RecrusiveDirectoryIterator($dir),
    RecursiveTreeIterator::BYPASS_KEY,
    CachingIterator::CALL_TOSTRING
);
$files = iterator_to_array($it);
natsort($files);
echo implode("\n", $files);

or

$it = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($dir),
    RecursiveIteratorIterator::SELF_FIRST
);
$files = iterator_to_array($it);
$files = array_map(function($file) { return (string) $file; }, $files);
natsort($files);
echo implode("\n", $files);

Edit: Based on your edit, here's how I would solve it:

function BuildTree($it, $separator = '  ', $level = '') {
    $results = array();
    foreach ($it as $file) {
        if (in_array($file->getBasename(), array('.', '..'))) {
            continue;
        }
        $tmp = $level . $file->getBaseName();
        if ($it->hasChildren()) {
            $newLevel = $level . $separator;
            $tmp .= "\n" . BuildTree($it->getChildren(), $separator, $newLevel);
        }
        $results[] = $tmp;
    }
    natsort($results);
    return implode("\n", $results);
};
$it = new RecursiveDirectoryIterator($dir);
$tree = BuildTree($it);

It's a pretty simple recursive parser, and does the natural sort on each level.

Hossein

Don't know about SPL iterators, but for your iterator you should put the items in an array, then sort them and add them to $tree. I modified the function current but didn't test it:

function current()
{
    $tree = '';

    $treeitems = array();
    for ($l=0; $l < $this->getDepth(); $l++) {
        //NOTE: On this line I think you have an error in your original code:
        //      This ? ' ' : ' ' is strange
        $treeitems[] = $this->getSubIterator($l)->hasNext() ? ' ' : ' ';
    }
    $treeitems.sort();
    for each ($treeitems as $treeitem)
        $tree .= $treeitem;

    return $tree . ($this->getSubIterator($l)->hasNext() ? ' ' : ' ') 
           . $this->getSubIterator($l)->__toString();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!