phparrayssortingusortcustom-sort

Get highest and lowest values from an array where order is like "AAA", "AA", "A", "BBB", "BB", etc


What I'm trying to do is creating a custom rating system like this:

AAA - Highest rating
AA
A
BBB
BB
B
CCC
CC
C - Lowest rating

In which AAA is the highest and C the lowest. For this this to work I need PHP to know which rating is the highest, lowest and everything in between and evaluate series of ratings based on that. I allready figured out how to create a sorting with usort() like so:

$ratings = array("a" => "AAA", "b" => "AA", "c" => "A", "d" => "BBB", "e" => "BB", "f" => "B", "g" => "CCC", "h" => "CC", "i" => "C");
$sortedRatings = usort($ratings, "cmp_function");

This will return an array neatly sorted from highest priority to lowest. Now I need to go ahead and use this sorting to get the highest and lowest rating from an array like this one:

$ratingHistory = array("BB", "B", "CCC", "C", "BB");

So how could I go about getting the highest and lowest value from $ratingHistory based on the sorting as in $sortedRatings ? I hope someone can help me out with this one. If my problem isn't completely clear to you, drop a comment so I can try to explain further.

Edit:

Just to be clear. The expected outcomes would be:

Highest: BB
Lowest: C

Solution

  • This solution works with your original $ratings array and — through usort() — sort $ratingHistory:

    $ratings = array("a" => "AAA", "b" => "AA", "c" => "A", "d" => "BBB", "e" => "BB", "f" => "B", "g" => "CCC", "h" => "CC", "i" => "C");
    $ratingHistory = array("BB", "B", "CCC", "C", "BB");
    
    usort
    (
        $ratingHistory,
        function( $a, $b ) use( $ratings )
        {
            return strcmp( array_search( $a, $ratings ), array_search( $b, $ratings ) );
        }
    );
    
    $result = array( 'max'=>current($ratingHistory), 'min'=>end($ratingHistory) );
    
    print_r( $result );
    

    Will print:

    Array
    (
        [max] => BB
        [min] => C
    )
    

    Performance:

    I have compared the performance of above example with a foreach(), an array_map() (all cases with both associative and enumerated array as $ratings and with different $ratingHistory sizes). The usort() method is in anyhow far the more efficient. This because you have anyway to iterate complete array, but with usort you can use less commands/functions/comparisons.