我有一个这样的数组:
[1303] => Array
(
[Name] => Al****
[Total] => 479896.025
)
[13047] => Array
(
[Name] => An****
[Total] => 1999.871
)
[13065] => Array
(
[Name] => Ao****
[Total] => 3947.761
)
[13054] => Array
(
[Name] => Ba****
[Total] => 15666.826
)
[13020] => Array
(
[Name] => Bb****
[Total] => 22366.6456
)
[13016] => Array
(
[Name] => Be****
[Total] => 8307.389
)
数组按名称排序。我需要根据总数为每个数组项分配排名。在上面的例子中,项目1303应该具有等级1,项目13020应该具有等级2,依此类推;数组必须保持其现有的排序。最简单的方法是什么?预期产出:
[1303] => Array
(
[Name] => Al****
[Total] => 479896.025
[Rank] => 1
)
[13047] => Array
(
[Name] => An****
[Total] => 1999.871
[Rank] => 6
)
[13065] => Array
(
[Name] => Ao****
[Total] => 3947.761
[Rank] => 5
)
[13054] => Array
(
[Name] => Ba****
[Total] => 15666.826
[Rank] => 3
)
[13020] => Array
(
[Name] => Bb****
[Total] => 22366.6456
[Rank] => 2
)
[13016] => Array
(
[Name] => Be****
[Total] => 8307.389
[Rank] => 4
)
答案 0 :(得分:3)
使用Total值对数组进行排序:
function totalSort($a, $b) {
if ($a['Total'] > $b['Total']) {
return -1;
} else if ($a['Total'] < $b['Total']) {
return 1;
} else {
return 0;
}
}
uasort($array, 'totalSort');
添加Rank元素:
$i = 1;
foreach ($array as &$element) {
$element['Rank'] = $i++;
}
再次按名称对数组排序(如果需要):
function nameSort($a, $b) {
if ($a['Name'] > $b['Name']) {
return -1;
} else if ($a['Name'] < $b['Name']) {
return 1;
} else {
return 0;
}
}
uasort($array, 'nameSort');
答案 1 :(得分:1)
我会做这样的事......
答案 2 :(得分:1)
我认为你应该做两个步骤:
仔细选择一个最符合您需求的sort function。我想uasort()
会这样做:
function cmp($a, $b) {
if( $a['Total'] == $b['Total']){
return 0;
}
return ($a['Total'] < $b['Total']) ? -1 : 1;
}
uasort( $array, 'cmp');
可能foreach
循环是最简单的方法:
$i = 1;
foreach( $array as &$item){
$item['Rank'] = $i;
$i++;
}