[英]PHP sorting array values from within an array
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. 键的值是一个数组,具有2个值:百分比值和总值。
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." 在上述情况下,“ Janice K.” has a percentage of 90.00, and she has 40 sales. 拥有90.00的百分比,并且她有40笔销售。 In a nutshell, she has made 40 sales, and 90% of them have cleared. 简而言之,她完成了40笔交易,其中90%已结算。
Is it possible to sort based on the $value of a $key, if it's an array? 如果它是一个数组,是否可以根据$ key的$ value进行排序?
uasort()
sorts an array with a user-defined function and maintains index assocation. uasort()
使用用户定义的函数对数组进行排序,并维护索引关联。 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
)
)
$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. edit2:添加按销售额排序(desc)等于百分比。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.