简体   繁体   中英

PHP sort array 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);

因为它是一个路径,所以只需通过basename()映射数组,然后根据它进行排序:

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

Try this

function cmp($a, $b) {
   // if equal, don't do much
   if ($a == $b) {
       return 0;
   }

   $explodedA = explode('/', $a);
   $explodedB = explode('/', $b);
   $yearPartA = $explodedA[count($explodedA) - 1];
   $yearPartB = $explodedB[count($explodedB) - 1];


   if ($explodedPartA == $explodedPartB) { // compare full string
      return ($a < $b) ? -1 : 1;
   }

   return ($yearPartA < $yearPartB) ? -1 : 1;
}

// actual sort of the array $path (e.g. the whole point)
usort($path, "cmp");

Consider, however that you'd probably be doing 'explode' several times for each array element and that it might be cheaper to work a bit on the array first. Not sure how big your array is... Do some testing.

$array = ['data/pictures/alice/1980','data/pictures/alice/1985','data/pictures/bob/1981','data/pictures/bob/1985','data/pictures/bob/1987','data/pictures/bob/1989'];

uasort($array, function($a,$b) {
    $y1 = array_pop(explode('/', $a));
    $y2 = array_pop(explode('/', $b));
    if($y1===$y2) {
       // if year the same use other criteria
       if($a===$b) {
          return 0;
       }
       return $a>$b?-1:1;
    };
    return $y1>$y2?-1:1;
});

使用usort并在自定义函数中用“/”分解字符串并比较数组的最后部分。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM