1

I have an array where the Key is the sales person. The value of the key is an array, with 2 values: A percentage value, and a total value.

In a nutshell, I am trying to sort the Highest percentage value on top.

$sales = array(
    "Johnny Smith" => array(75.25,45), 
    "Ash Han" => array(55.67, 99), 
    "Janice K." => array(90.00, 40)
);

I've tried a few arrangements or array sorting functions, and none are good enough to even display, since they don't have examples where the array value is an array to sort from.

The end result is where I'd like to display which sales person has the highest percentage to lowest percentage. In the case above, "Janice K." has a percentage of 90.00, and she has 40 sales. In a nutshell, she has made 40 sales, and 90% of them have cleared.

Is it possible to sort based on the $value of a $key, if it's an array?

2 Answers 2

3

uasort() sorts an array with a user-defined function and maintains index assocation. Here's an implementation example using an anonymous function.

uasort($sales, function($a, $b) {
    return $b[0] - $a[0];
});
print_r($sales);

The above will yield

Array (
    [Janice K.] => Array (
            [0] => 90
            [1] => 40
    )
    [Johnny Smith] => Array (
            [0] => 75.25
            [1] => 45
    )
    [Ash Han] => Array (
            [0] => 55.67
            [1] => 99
    )
)
1
  • @coffeemonitor this is quite literally what I had written at first. however, the problem I found is that if abs($b[0]-$a[0]) is less than 1, things get out of order. The return value appears to be casted to an integer which truncates values less than abs(1) to 0 which means "these are equal" (which they are not). This is why I changed my answer to return -1,0,1. Perhaps a simple ($b[0]-$a[0])*100 would be easier. Commented Jan 30, 2012 at 16:20
1

use uasort.

$sales = array(
    "Johnny Smith" => array(75.25,45), 
    "Ash Han" => array(55.67, 99), 
    "Janice K." => array(55.00, 40)
);

//comparison function.
function cmp($a,$b){
    //if the percentages (key 0) are equal...
    if($b[0]==$a[0]){
        //check sales count (key 1)
        if($b[1]==$a[1]){
            //if both are equal, return 0
            return 0;
        }
        //return -1 or 1 based on which sales are higher
        return $b[1]<$a[1]?-1:1;
    }
    //return -1 or 1 based on which percentage is higher
    return $b[0]<$a[0]?-1:1;
}
//run sort on sales using custom compare function.
uasort($sales, 'cmp');
//print the values.
echo '<pre>';
print_r($sales);

edit: added comments. edit2: added sort by sales (desc) is percent is equal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.