dongzhui9936 2015-12-12 18:28
浏览 60
已采纳

在php中,如何根据特定的(在本例中为最后一个)路径片段对路径数组进行排序?

I have an array like so:

[0] => /home/user/public_html/things/1 - First thing/
[1] => /home/user/public_html/things/3 - Third thing/
[2] => /home/user/public_html/things/2 - Second thing/

What's the straightforward way to sort this array so the 'things' go 1, 2, 3?

I've used natsort() on just the last path-fragment but it's not proving straightforward to use... I chopped the rest of the path off, sorted, then put it back on but that's ugly and it can change in the mean time so I'm hoping for a better way than that.

Any and all suggestions would be greatly appreciated, I'm sure there's several ways to approach this :)

  • 写回答

4条回答 默认 最新

  • dongza3124 2015-12-12 19:43
    关注

    Taking your question as it stands (sort an array of paths based on a specific path-fragment), I thought of a function that would allow you to specify the fragment you want the paths to be sorted on.

    As the paths in the example only differ in their last part, the above is not very interesting when applied on that example. So I will use a slightly different list:

    $paths = [
        '/home/user/public_html/things/sub/1',
        '/home/user/public_html/things/3',
        '/home/admin/public_html/things/2'
    ];
    
    function build_sorter($part) {
        return function ($a, $b) use ($part) {
            return strnatcmp(
                implode("/", array_slice(explode("/", $a), $part)),
                implode("/", array_slice(explode("/", $b), $part))
            );
        };
    }
    
    // sort by second part in paths:
    usort($paths, build_sorter(2));
    print_r ($paths);
    

    The output generated has put the "admin" folder first:

       Array (
         [0] => /home/admin/public_html/things/2
         [1] => /home/user/public_html/things/3
         [2] => /home/user/public_html/things/sub/1
       ) 
    

    Sorting by the last part would go like this:

    usort($paths, build_sorter(-1));
    print_r ($paths);
    

    Output:

       Array (
         [0] => /home/user/public_html/things/sub/1
         [1] => /home/admin/public_html/things/2
         [2] => /home/user/public_html/things/3
       ) 
    

    So the argument you pass to builder_sort is the offset (positive from left, negative from right) of the part of the paths you want to base your sort on.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘