phparrayssorting

Sort an array of strings by their 3rd character, then 4th, then 2nd


I'm trying to sort an array with school class names however when I use an alphabetical sorting function they wouldn't sort by grade year.

Alphabetical sorting:

Array
(
   "LA2A",
   "LB1A",
   "LG2A",
   "LG3A",
   "LH2A",
   "LH3A",
   "LH4A",
   "LH5A",
   "LV4A",
   "LV5A",
   "LV6A"
)

This is what I would like to achieve:

Array
( 
   "LB1A",
   "LA2A",
   "LG2A",
   "LH2A",
   "LG3A",
   "LH3A",
   "LH4A",
   "LV4A",
   "LH5A",
   "LV5A",
   "LV6A"
)

So, how can I sort an array (in PHP) by first the third character, then the fourth and finally the second character.


Solution

  • Demo using usort

    $test = array(
       "LA2A",
       "LB1A",
       "LG2A",
       "LG3A",
       "LH2A",
       "LH3A",
       "LH4A",
       "LH5A",
       "LV4A",
       "LV5A",
       "LV6A"
      );
    
    
    
    //sort by first the third character, then the fourth and finally the second character.  
    function mySort($left, $right) {
    
       $left = $left[2].$left[3].$left[1];
       $right = $right[2].$right[3].$right[1];
    
       return strcmp($left, $right);
    }
    
    
    usort($test, 'mySort');
    

    $test is now :

    Array (
       [0]  => LB1A
       [1]  => LA2A
       [2]  => LG2A
       [3]  => LH2A
       [4]  => LG3A
       [5]  => LH3A
       [6]  => LH4A
       [7]  => LV4A
       [8]  => LH5A
       [9]  => LV5A
       [10] => LV6A
    )