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条)

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路