Bouke
Bouke

Reputation: 660

Sorting by nth character in PHP

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.

Upvotes: 0

Views: 1311

Answers (2)

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
)

Upvotes: 2

SheetJS
SheetJS

Reputation: 22905

The easiest way to do this is to apply something like the https://en.wikipedia.org/wiki/Schwartzian_transform

$arr = ...;
function add_key($x) { return $x[2] . $x[3] . $x[1] . $x; }
function rem_key($x) { return substr($x, 3); }
$tmp = array_map("add_key",$arr);
sort($tmp);
$res = array_map("rem_key",$tmp);

add_key adjusts each string by copying the sort key to the front. Then we sort it. rem_key gets rid of the key.

Upvotes: 2

Related Questions