phparrayssortingpathbasename

Sort array of directory path strings by lowest directory (ending substring)


I want to sort this array by year:

Array
(
    [0] => data/pictures/alice/1980
    [1] => data/pictures/alice/1985
    [2] => data/pictures/bob/1981
    [3] => data/pictures/bob/1985
    [4] => data/pictures/bob/1987
    [5] => data/pictures/bob/1989
)

Expected result:

Array
(
    [0] => data/pictures/alice/1980
    [1] => data/pictures/bob/1981
    [2] => data/pictures/alice/1985
    [3] => data/pictures/bob/1985
    [4] => data/pictures/bob/1987
    [5] => data/pictures/bob/1989
)

I've already tried different sort functions without success.

Example:

asort($paths, SORT_STRING | SORT_FLAG_CASE);

sort($path, SORT_NUMERIC);

Solution

  • Since it's a path just map the array through basename() and then sort based on that:

    array_multisort(array_map('basename', $paths), SORT_ASC, $paths);