phparrayssortingmultidimensional-arrayaccent-insensitive

Sort rows of a 2d array based on a column's text which may contain accented characters


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 so that accented characters are positioned near their non-accented letter?


Solution

  • 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'];
    }