0

Im attempting to sort an array by a part(substring) of one of the values. Most of the examples shown just sort by value.

I need to sort by the last part of the name, so '4/01.02' would be '02'. '01' would be sorted gainst '02' etc.

I managed to get this to work by adding explode to the value check, but it doesnt sort the numbers and letters in correct order.

The numbers seem correct, but when it hits letters it goes in odd order.

  • How can I get the end letters to sort as desired?
  • How can I move values that begin with letters after the numbers?

RESULT: LG1, 01, 02C, 02B, 02D, 02A, 03....

DESIRED: 01, 02A, 02B, 02C, 02D, 03, LG1....

EXAMPLE ARRAY

Array
(
    [0] => Array
    (
        [room_id] => 4-01-1
        [name] => 4/01.02A
        [type] => office
    )

    [1] => Array
    (
        [room_id] => 4-01-2
        [name] => 4/01.01
        [type] => office
    )
    [2] => Array
    (
        [room_id] => 4-01-3
        [name] => 4/01.03
        [type] => office
    )
    [3] => Array
    (
        [room_id] => 4-01-4
        [name] => 4/01.02B
        [type] => office
    )
);

PHP

uasort($rooms, function($a, $b) 
{
    return explode('.', $a['name'])[1] - explode('.', $b['name'])[1];
});
Orbitall
  • 611
  • 11
  • 36

1 Answers1

2

You can try using strcmp in your comparison function instead of subtracting:

return strcmp(explode('.', $a['name'])[1], explode('.', $b['name'])[1]);

When you subtract, the letters will be converted to integer 0. The comparison using strcmp will be case sensitive, but from the data in your example it looks like that should be okay.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80