Search code examples
phpassociative-arrayusort

Sort Associative PHP Array By Number Then By String


I have an associative array in PHP that is created from a SQL Query. I've been sorting by just one column, but now I need to change the code to sort by two columns.

The two columns consist of a FLOAT and a STRING: $array["FinalValue"] = float and $array["Category"] = string

I'm using this right now to just sort by the one column (FinalMulti) which is a FLOAT:

usort($categorylist, function($a, $b){
   if((float) $b['FinalMulti'] == (float) $a['FinalMulti']) return 0;
   return ((float) $b['FinalMulti'] < (float) $a['FinalMulti']) ? - 1 : 1;
});

I've searched the site on how to do this and found an example that sorted by STRING then INTEGERS, but nothing quite in my order and nothing that builds on the code I'm currently using.

The other examples used strcmp and I've inserted it in few place and it doesn't work. For example, I tried:

usort($categorylist, function($a, $b){
   if((float) $b['FinalMulti'] == (float) $a['FinalMulti']) {
      return strcmp($b['CategoryName'], $a['CategoryName']);
   }
   
   return ((float) $b['FinalMulti'] < (float) $a['FinalMulti']) ? - 1 : 1;
});

I know strcmp compares strings so I feel like that there should be an if statement, but I don't know what I would return. While I'm decent at programing, my understanding of usort is not strong.

In the end, ["FinalMulti"] needs to be sorted DESC from highest to lowest while ["CategoryName"] needs to be sorted in alphabetical order (A to Z). The first letter in all ["CategoryName"] strings are capitalized.

Thanks in advance!


Solution

  • You can use array_multisort with array_column:

    array_multisort(
      array_column($categorylist, 'FinalMulti'), SORT_DESC, 
      array_column($categorylist, 'CategoryName'), SORT_ASC, 
      $categorylist
    );
    

    3v4l.org demo