PHP sorting array values from within an array

若如初见. 提交于 2021-01-28 19:01:30

问题


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?


回答1:


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
    )
)



回答2:


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.



来源:https://stackoverflow.com/questions/9041909/php-sorting-array-values-from-within-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!