【问题标题】:PHP Symfony Finder: sort by directory depthPHP Symfony Finder:按目录深度排序
【发布时间】:2019-09-25 21:11:16
【问题描述】:

我使用 Symfony 的 Finder 在目录中搜索特定文件名。我需要按目录深度对结果进行排序。深度为 0 的文件(根文件夹)应位于顶部,深度为 7 的文件应位于最后。

可用的排序机制仅按名称排序,不考虑目录深度。例如。 “按名称排序”

$finder->sortByName(true);
a/acme/conf.yaml
conf.yaml
m/conf.yaml
o/data/a/b/c/d/conf.yaml
t/data/conf.yaml
w/data/conf.yaml

我希望conf.yaml 位于顶部,o/data/a/b/c/d/conf.yaml 应位于底部。

我在 Symfony (https://github.com/symfony/symfony/issues/11289) 中发现了一个问题,但没有关于整洁排序方法的建议。

【问题讨论】:

    标签: php file symfony sorting finder


    【解决方案1】:

    Symfony 允许设置自定义排序机制:https://symfony.com/doc/current/components/finder.html#sorting-results

    为了比较深度,我计算路径中的斜线并按照此答案中的建议对计数进行排序:https://stackoverflow.com/a/2852918/3894752

    这对于目录深度(

    如果两个文件的深度相同,则再次使用文件名进行排序。

    $finder->sort(static function (\SplFileInfo $a, \SplFileInfo $b) {
        $depth = substr_count($a->getRealPath(), '/') - substr_count($b->getRealPath(), '/');
        return ($depth === 0)? strcmp($a->getRealPath(), $b->getRealPath()) : $depth;
    });
    
    conf.yaml
    m/conf.yaml
    a/acme/conf.yaml
    t/data/conf.yaml
    w/data/conf.yaml
    o/data/a/b/c/d/conf.yaml
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      • 1970-01-01
      • 2018-03-21
      • 1970-01-01
      • 2015-08-21
      • 1970-01-01
      相关资源
      最近更新 更多