9

I am using this to sort according to last name:

  usort($fb_friends['data'], "custom_sort");          
  function custom_sort($a,$b) { 
    return $a['last_name']>$b['last_name'];
  }

  foreach($fb_friends['data'] as $friend) { 
    echo '<br>'; 
    echo $friend['name']; 
  } 

But - when in last name is accent, e.g. Šiko, Áron, etc, these names are at the end. How can I sort it properly?

peter
  • 4,289
  • 12
  • 44
  • 67
  • Does this answer your question? [How can I sort an array of UTF-8 strings in PHP?](https://stackoverflow.com/questions/7929796/how-can-i-sort-an-array-of-utf-8-strings-in-php) – hanshenrik Jan 05 '23 at 14:57

2 Answers2

17

Use multi-byte string functions. There is a function called strcoll which seems to suit your needs.

More info:


EDIT: added Peter's working code, below

setlocale(LC_COLLATE, 'sk_SK.utf8');

usort($fb_friends['data'], 'custom_sort');

function custom_sort($a, $b) {
    return strcoll ($a['last_name'], $b['last_name']);
}

foreach ($fb_friends['data'] as $friend) {
    echo '<br>';
    echo $friend['name'];
}
JerabekJakub
  • 5,268
  • 4
  • 26
  • 33
J. Bruni
  • 20,322
  • 12
  • 75
  • 92
  • 1
    thank you! this works for me: setlocale(LC_COLLATE, 'sk_SK.utf8'); usort($fb_friends['data'], "custom_sort"); function custom_sort($a,$b) { return strcoll ($a['last_name'], $b['last_name']); } foreach($fb_friends['data'] as $friend) { echo '
    '; echo $friend['name']; }
    – peter Mar 11 '12 at 12:46
  • What if the strings are part of a multiple columns array and we want to sort on multiple columns? – Pierre Mar 22 '16 at 18:32
8

What comes first?

  • A
  • a
  • ث

This is defined by a Collation.

PHP has the Collator class for this: https://www.php.net/manual/en/class.collator.php

Example:

$array = [ 'A', 'a', '文', 'ث' ];

// Brazilian Portuguese
$collator = new Collator('pt_BR');

$collator->asort( $array );

print_r( $array );

Returns:

Array
(
    [1] => a
    [0] => A
    [3] => ث
    [2] => 文
)

Now with a Chinese collation new Collator('zh'):

Array
(
    [2] => 文
    [1] => a
    [0] => A
    [3] => ث
)

You can try it yourself here: https://3v4l.org/0vsBR

Lucas Bustamante
  • 15,821
  • 7
  • 92
  • 86