Search code examples
phpsortingcollectionsusort

Sort multidimensional array by string in value by collator


This function work well until PHP version 8.1

usort($list, function($a, $b) {
    $retval = $a[0] <=> $b[0];
    if ($retval == 0) {
        $collator = collator_create('da');
        $arr = array($a[3], $b[3]);
        collator_asort($collator, $arr, Collator::SORT_STRING);
        return array_pop($arr) == $a[3];
    }
    return $retval;
});
$list = array(array(1,0,"aa"),array(0,0,"å"),array(1,0,"b"),array(0,0,"a"));

Result:

Array
(
    [0] =Array
    (
        [0] =0
        [1] =0
        [2] =a
    )

    [1] =Array
    (
        [0] =0
        [1] =0
        [2] =å
    )

    [2] =Array
    (
        [0] =1
        [1] =0
        [2] =b
    )

    [3] =Array
    (
        [0] =1
        [1] =0
        [2] =aa
    )
)

How to write it for PHP 8.1?

Sort the array in the same way just in PHP8.1


Solution

  • Don't use collator_asort(); your test is then returning a true/false value. Use Collator::compare(), which returns the proper -1/0/1 result that usort() wants.

    And don't create a new collator every time the comparison function is called, create it once.

    $collator = collator_create('da');
    usort($list, function($a, $b) use ($collator) {
        $retval = $a[0] <=> $b[0];
        if ($retval == 0) {
            $retval = $collator->compare($a[3], $b[3]);
        }
        return $retval;
    });