Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two sorting methods in PHP?

Tags:

php

sorting

How to sort a list of people by their family names, according to local alphabet and retaining their IDs? I've found the relevant pieces of code, just can't put it all together. So the initial array is:

$names = array(
    "12" =>     "John Zareem",
    "134" =>    "Elin Ärlik",
    "24" =>     "Katrin Šüüva",
    "11" =>     "Mati Winterberg"
);

Now to sort them by family names:

function lastNameSort($a, $b) {
    $aLast = end(explode(' ', $a));
    $bLast = end(explode(' ', $b));
    return strnatcmp($aLast, $bLast);
}
uasort($names, 'lastNameSort');

Works, but it's by international alphabet. To sort an array by local (for example Estonian) alphabet:

setlocale(LC_ALL, 'et_EE.utf8');
asort($names, SORT_LOCALE_STRING);

Works regarding the local alphabet, but it's not by family names. Would it be possible to combine these two sorting methods? Thanks in advance!

like image 371
LeFunk Avatar asked Jul 02 '26 23:07

LeFunk


1 Answers

There's not well known strcoll() for that, which can be used in user-defined callback:

setlocale(LC_ALL, 'et_EE.utf8');
uasort($names, function($x, $y)
{
   return strcoll(
      end(preg_split('/\s+/', $x)),
      end(preg_split('/\s+/', $y))
   );
});

Result would be

array(4) {
  [24]=>
  string(15) "Katrin Šüüva"
  [12]=>
  string(11) "John Zareem"
  [11]=>
  string(15) "Mati Winterberg"
  [134]=>
  string(11) "Elin Ärlik"
}
like image 162
Alma Do Avatar answered Jul 04 '26 13:07

Alma Do