Search code examples
phparrayssortingalphabet

Sort array alphabetical as nordic/locale order


I'm sorry - im learning PHP. Looking for help to sort array by name - but as my locale alphabet.

I would like to sort array as nordic alpabet and I would want to leave rows with numbers last, I tried with multisort with setlocale but I could not make to sort correctly.

My example array:

Array(
[3] => Array
(
    [0] => WP_Term Object(
        [name] = 3-title-with-starting-3
    )
)
[9] => Array
(
    [0] => WP_Term Object(
        [name] = 9-title-with-starting-9
    )
)   

[A] => Array
(
    [0] => WP_Term Object(
        [name] = A-title-with-starting-A
    )
    [1] => WP_Term Object(
        [name] = A-title-with-starting-A2
    )       
)
[Z] => Array
(
    [0] => WP_Term Object(
        [name] = Z-title-with-starting-Z
    )
    [1] => WP_Term Object(
        [name] = Z-title-with-starting-Z
    )       
)
[Ö] => Array
(
    [0] => WP_Term Object(
        [name] = Ö-title-with-starting-Ö
    )
    [1] => WP_Term Object(
        [name] = Ö-title-with-starting-Ö
    )       
))  

Solution

  • You can utilize the Collater class in php. Here's an example. I'm not a linguist, but I think using a Norwegian locale would probably help.

    <?php
    $letters = ['Ö', 'X', 'A', 'Z', '2', '99', 'D'];   
    //Make a Collator object with the locale code of the language to sort.
    $collator = new Collator('nb'); //nb    Norwegian Bokmål
    
    //Use Collator::sort() instead of sort() [returns a numerical array];
    //or Collator::asort() instead of asort [maintains the keys of an associative array].
    $collator->sort($letters, Collator::SORT_REGULAR);
    var_dump($letters);