Search code examples
phparrayssortingnumericstable-sort

Stable sort a flat array only by its trailing number


This is the array

$array = array(
   'list[P] = 1',
   'list[A] = 1',
   'list[F] = 2',
   'list[B] = 1'
);

This is the output I want

[0] => list[P] = 1
[1] => list[A] = 1
[2] => list[B] = 1
[3] => list[F] = 2

notice `list[P]` remains at the top because it is the first with value 1. So only numeric sorting.

Solution

  • Try taking a look at this documentation.

    As you are trying to sort a specific part of the value, then you need to write your own comparator, and therefore the only method available is the usort function.

    The uksort function takes two attributes, the array and the method name that you wish to use to do your comparison. You then write this method, which takes two values as a parameters, and return a true of false, depending on whether it is greater than or less than.

    Therefore, you would have to substring the values coming in, to only compare the numbers.

    The following code sample seems to work

    function cmp($a, $b)
    {
        $a = substr($a, -1);
        $b = substr($b, -1);
        return $a >= $b;
    }
    
    $array = array(
       'list[P] = 1',
       'list[A] = 1',
       'list[F] = 2',
       'list[B] = 1'
    );
    
    usort($array, "cmp");
    
    var_dump($array);
    

    The same code, only using PHP's anonymous function:

    $array = array(
       'list[P] = 1',
       'list[A] = 1',
       'list[F] = 2',
       'list[B] = 1'
    );
    
    usort(
       $array,
       function ($a, $b){
          $a = substr($a, -1);
          $b = substr($b, -1);
          return $a >= $b;
       }
    );
    
    var_dump($array);